a better approach than storing mysql password in plain text in config file?

Personally, I store sensitive information such as database connection details in a config.ini file outside of my web folder’s root. Then in my index.php I can do:

$config = parse_ini_file('../config.ini');

This means variables aren’t visible if your server accidentally starts outputting PHP scripts as plain text (which has happened before, infamously to Facebook); and only PHP scripts have access to the variables.

It’s also not reliant on .htaccess in which there’s no contingency if your .htaccess file is moved or destroyed.

Caveat, added 14 February 2017: I’ll now store configuration parameters like this as environment variables. I’ve not used the .ini file approach for some time now.


Since your code will need the password there is no perfect security. But you can make it hard to recover.

I put some hash in my web config, as an environment variable, say MYSQL_PASS_HASH

Then I do something like md5(getenv('MYSQL_PASS_HASH').'gibberish$qwefsdf') which is then the password. Of course you should unsetenv after that if you're paranoid.

Your password will not literally be stored somewhere, and it can be recovered only when someone has both you web config and your database include.

This happens in a file outside of the webroot (don't put all your trust in .htaccess).


Keeping your config files outside of your document root is a popular way of improving the security of config files.


Certainly you should never store a password in a plain text file within the document root. What further steps you take to secure it will depend on the level of access you have to configure your webserver.

You could define the password in php.ini (or via the ini setting in the Apache config or .htaccess). Or set it in the environment when you start up your webserver.

There's no point in just encrypting the password - that means you need to store a decryption key - unless you use the user supplied password with quorum authentication to decrypt the password (but this prevents non-authenticated sessions from accessing the db, and gets messy when you need to add new users to the quorum).

If its a cheap hosting package and you have no accessible storage outside the document root then storing the password in a php include file within should prevent it being exposed (file will be parsed by php intead of downloaded). Alternately simply naming the file with a '.ht' at the beginning may prevent remote access.

Note your second option is somewhat redundant - if someone can do that much damage to your code then they don't need to extract the password from the running code.

Really there's no solution to the problem.

C.