Today I read an interesting article in O'Reilly's PHP Cookbook: Keeping Passwords Out of Your Site Files. When your passwords are in a hidden file (a file which can't normally be reached from the internet), it's much harder for unprivileged visitors to get your valuable credentials. In this example: username and password for your MySQL database.
How to do this:
First, create a file in /usr/local/apache/
(this folder can't be reached from the internet without SSH or FTP root permissions). For example, name this file database-passwords. The contents of this file is:
SetEnv DB_USER "username"
SetEnv DB_PASSWORD "password"
where "username" and "password" are your real username and password.
Add this line to the appropriate <VirtualHost> settings in /etc/apache2/apache2.conf:
Include /usr/local/apache/database-passwords
Restart Apache
Now, make a folder in your website root named mysql
add a file to this folder, named .htaccess (the contents of this file: deny from all), also add a file to the mysql folder named mysql-details.php, the contents of this file is:
<?php
$host = "127.0.0.1";
$user = $_SERVER['DB_USER'];
$password = $_SERVER['DB_PASSWORD'];
$dbname = "mydatabase";
$tablename = "mytable";
$db = mysql_connect($host, $user, $password) or die("no connection");
mysql_select_db($dbname,$db);
?>
where mydatabase and mytable are the real name for your database and table
Add this line to the php file in which you want to call the MySQL username and password:
include("mysql/mysql-details.php");
A big fat warning:
be sure no file exists in your website folder with the contents <?php phpinfo() ?> as with this command your credentials are revealed to the world (in the Apache Environment sector). Also, make sure not to expose the contents of $_SERVER in other ways, such as with the print_r() function. If you can prevent this, you're ready to go and you can be a bit more certain that your MySQL login credentials are safe from unprivileged eyes.
Recent Comments