Reputation: 12297
I've had lots of problems concealing database credentials needed for PHP classes. None of the "solutions" recommended worked so far.
1) PHP manual recommends to save the credentials in a different file: check! All my PHP database classes insert the credentials from a different file.
Typical db class
class database{
private static $dbc = null;
public static function get($page,$component = null){
if(self::$dbc === null) {
$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/some path/';
$file = 'pdo.php';
require( $root . $path . $file );
}
...more code...
credentials file
$dbhost = 'some.host';
$dbname = 'someDBname';
$dbuser = 'someUser';
$dbpass = 'somePassword';
2) Despite this, the file where I keep all the info in the web-host, the file can be sniffed or found.
How can I conceal this file, containing the database info, in order to have a REALLY secure website and database?
Upvotes: 0
Views: 351
Reputation: 5084
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
Upvotes: 2