Protecting Your Config Files in PHP

Craig Blanchette on Google+ on November 4th 2013

I recently answered a question on reddit, I figure why not use the content on my site:

Our company email is run on Exchange on our internal server and we have a few web sites hosted on Dreamhost currently that point the MX Records to our internal IP for Exchange email. My question is this: I've spoken with customer support at Dreamhost and confirmed that using the PHP mail() method requires SMTP authentication if you don't have email hosted on Dreamhost (we don't). I'm pretty green at webdev and I'm leery of some of the scripts with SMTP authentication I have seen. All of them I have seen use strings to store the username and password for an account. How is this secure? I don't want to put this in a PHP file on my website.

My response:

It's pretty common to do this, even for things like database connections. There are a few precautions you can take though

Don't place the config file in web root

If your web root is ~/public_html/, place the file in another folder: ~/app/config.php this way if php fails for some reason and starts spitting out your code in plain text, they won't be able to get to your file.

Protect with htaccess

Sometimes in shared hosting you don't really have that option so you can create a folder in your web root ~/public_html/app and then create a file ~/public_html/app/.htaccess and insert

deny from all

into the file. If somebody now tries to access your file from the browser they will get an access denied so it can't be run directly. Even if php fails apache will stop them. And if apache is down they likely won't be able to access the file anyway.

chmod your config file

This will vary greatly depending on your PHP handler. With suPHP you can probably get away with removing read/write access to everyone except for the owner since PHP is running as that user. If Apache needs access to your files, then you will need to grant read access to group, etc.

You can also remove execute permissions on the parent directory so if somebody did get in they couldn't get directory listings and find the filename.