How do I prevent exposing MySQL usernames and passwords in PHP code when establishing a connection?
It is never a good idea to store passwords in source code. Source code has the horrible tendency of becoming public. This can happen by an exposure in your version control system (google
aws key github to read some horror stories), you share the source code with someone, a but in your PHP configuration serves your source code, etc...
Also, you should be able to change your password on an independent schedule from source code upgrades. Something storing them in the same file prevents.
Instead, put the password in a configuration file. This file should be outside of the web root to reduce the likelihood that it will be incorrectly served to the user. Secure it with appropriate OS permissions. You can pass the password to your PHP via an environment variable.
Hanky 웃 Panky brings up good points. However, I'd like to add to them:
- You can mitigate damage by restricting connecting accounts by roles. Let's say you only allow searching on your website. Allowing only
SELECTstatements for that particular account will prevent anything else from running. This doesn't work if you have an account for each:
DELETE, as an attacker could combine the privileges and cause serious damage.
- You can also deny anyone except those with appropriate admin access to the website, whose login will likely be independent of the webhost. IP-based deny all, allow from , for example. Note that this won't completely protect you if you've been breached, nor will it protect you if your web host is the one accessing the database.
Only those with root/admin/shell access to your website can obtain the username and passwords, unless you improperly chmodded the files. If any of those are true, you have much bigger issues than having your MySQL user/pass known.
The typical answer is: store them in configuration files because code files are often published. A new trend seems to be to store it in environment variables, if you can control those when starting the server. On shared hosting this is not the case, and then configuration files are a fine option. After all, once someone gets to your filesystem, they could also change your source code and thereby do anything anyway.