14.1. Keeping Passwords Out of Your Site Files
Problem
You need to use a password to connect to a database, for example. You don’t want to put the password in the PHP files you use on your site in case those files are compromised.
Solution
Store the password in an environment variable in a file that the web server loads when starting up; then, just reference the environment variable in your script:
mysql_connect('localhost',$_SERVER['MYSQL_USER'],$_SERVER['MYSQL_PASSWORD']);
Discussion
While this technique removes passwords from the source code of your
pages, it does make them available in other places that need to be
protected. Most importantly, make sure that there are no publicly
viewable pages that call phpinfo( )
. Because phpinfo( )
displays environment variables available to scripts, it
displays the passwords put into environment variables.
Next, especially if you are in a shared hosting setup, make sure that the environment variables are set in such a way that they are available only to your virtual host, not to all shared hosting users. With Apache, you can do this by setting the variables in a separate file from the main configuration file:
SetEnv MYSQL_USER "susannah" SetEnv MYSQL_PASSWORD "y23a!t@ce8"
Inside the <VirtualHost>
directive for the
site in the main configuration file, include this separate file as
follows:
Include "/usr/local/apache/database-passwords"
Make sure that the separate file that contains the passwords (e.g., /usr/local/apache/database-passwords
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.