28 July, 2010

Secure MySQL connection on Godaddy virtual dedicated server

The Godaddy instructions on this are pretty hard to find and the default settings for open_basedir and directory permissions make it hard to do; so here is what I have done that works. You will need to be using SSH and your control panel (I use Plesk, but I doubt this is much different with cPanel and others).

The key security point is that your access codes to your MySQL database really should not be in your httpdocs directory. That is accessible to the world and although it is hard to grab the information from a .php file, it is not impossible. If the file sits above the httpdocs folder, it cannot be seen from the web.

So using SSH create a folder (one per domain, but if you use only one database for a number of sites it could be one for all) called mysql with

mkdir mysql

then still in SSH change the ownership to the normal owner of the domain with

chown [user] mysql

Now open up the conf directory to the same user with

chown [user] conf

Go to your control panel and create these two files

1. a file in conf called vhost.conf (content below) and

2. a file in mysql called mysql.php (content below)

Finally, either in SSH Restart the server with

/usr/local/psa/admin/bin/websrvmng -a -v

or you can do it from control panel.

content of vhost.conf (where x is the domain)

<directory /var/www/vhosts/x/httpdocs>

php_admin_value open_basedir "/var/www/vhosts/x/httpdocs:/tmp:/var/www/vhosts/x/mysql:"

</directory>

content of mysql.php

<?php

/*

THIS IS THE MASTER DATABASE CONNECTION FILE

IT SHOULD BE STORED ABOVE THE ROOT DIRECTORY IN MYSQL

AND SHOULD BE USED FOR ALL MYSQL CONNECTIONS

*/

mysql_connect("localhost", "[username]", "[password]") or die (mysql_error());

mysql_select_db("[database_name]") or die(mysql_error());

?>

To connect to the database add this in the relevant php scripts

include '/var/www/vhosts/[domain]/mysql/mysql.php';

Hope that helps someone save the time it took me to work it out...