I'd recommend putting them in environment variables. You can getenv
And you can set them through either a .env
(Symfony and Laravel are both using this: Example) file, or in a .htaccess
file as explained here.
Bonus: If you're paranoid, you can throw in a salt and use a hashed password, as explained here, but I doubt that this changes much.
Edit: In the comments it was suggestion by @deceze not to store the credentials file in the document root. That's definitely something you should follow.
Let me elaborate. Let's say your domain example.com points to www/foo/bar/example.com/
don't store the file in there like www/foo/bar/example.com/db.php
but store it a level up at www/foo/bar/db.php
that way it can't be accessed through the browser, but PHP can still access ist, through include
or require
. You can add ..
to a path to go one folder back. If you have it sitting in the document root, it could be accessed using http://example.com/db.php and if your server isn't configured properly (or you use another formal like db.yml
or something), it could serve the file and thus expose your credentials
Note: The db.php
file is just an example. As stated above, I'd strongly recommend using environment variables!
Edit 2:
To stick with your example and a PHP solution without using environment variables. You could use something like this:
// the db class
class database{
private static $dbc = null;
public static function get($page,$component = null){
if(self::$dbc === null) {
$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/../db/';
$file = 'pdo.php';
require( $root . $path . $file );
self::$dbc = new PDO($dsn, $dbUser, $dbPass);
}
return self::$dbc;
}
}
// the pdo.php file
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$dbUser = 'dbuser';
$dbPass = 'dbpass';
The file structure would be something like
www
foo
yourwebsite
.htaccess
index.php
foobar.php
db
pdo.php
The website example.com would point to www/foo/yourwebsite