Recipe 14.2 Keeping Passwords Out of Your Site Files
14.2.1 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.
14.2.2 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',$_ENV['MYSQL_USER'],$_ENV['MYSQL_PASSWORD']);
14.2.3 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) is not
readable by any users other than the one that controls the
appropriate virtual host. When Apache starts up and is reading in
configuration files, it's usually running as root,
so it is able to read the included file.
14.2.4 See Also
Documentation on Apache's Include
directive at
http://httpd.apache.org/docs/mod/core.html#include.
|