0

Using PHP, is it alright to store database credentials in $_SESSION? I am looking for a way to avoid including config files every time I need to use config vars.

5
  • 2
    This sounds like an XY Problem to me. Commented Aug 10, 2017 at 17:50
  • 3
    there's nothing wrong in having a config file included all the time! Commented Aug 10, 2017 at 17:50
  • It's not really a good idea to use $_SESSION for this, because it seems like it would be slower Commented Aug 10, 2017 at 17:51
  • Maybe Jeff haha. Using session vars just seemed easier to me. But maybe not :P Commented Aug 10, 2017 at 17:52
  • @ZachAbrams including a config file is really easy. Most config files are near the root of your project, you can include them on any page by doing include_once $_SERVER["DOCUMENT_ROOT"].'/path/to/config', the path will start from the root folder of your project. Commented Aug 10, 2017 at 17:53

1 Answer 1

1

I would suggest sticking with the config file, as it allows changes in real time, if you change the config then this data will change instantly for any users that are online, where sessions would have to be set again every time it's changed. Always including a config may be easier than you think.

You can include a file using a path from your directory root, like this:

<?php 
   include_once $_SERVER['DOCUMENT_ROOT']."/path/to/config.php";
?>

Where the path should be from your document root, basically from the root of your project. A lot of the time people keep this file in their root, so if your config file is at http://example.com/config.php

using this include will load it from any php file in your project.

<?php 
   include_once $_SERVER['DOCUMENT_ROOT']."/config.php";
?>

Also, as Qirel mentioned:

The config should be stored outside the public folders - only accessible by the server (and not directly in the browser).

Sign up to request clarification or add additional context in comments.

1 Comment

Just a note, include isn't a function, so the parenthesis isn't needed. Also the config should be stored outside the public folders - only accessible by the server (and not directly in the browser).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.