Skip to content
Home » Web » PHP » Hide Database Connection File

Hide Database Connection File

A database connection file may contain confidential information like the following:

$user = "steven";
$pass = "password";
$options = "...";
$dbh = new PDO("...", $user, $pass, $options);

The confidential information includes database name, username and password for connection. Therefore, putting your database connection file in the document root of httpd might leave chances for hackers to attack your data.

A better solution is to move the file out of document root of httpd. For instance, if the database connection file is under the document root: /var/www/html/, you can create a directory /var/www/db outside the document root for your database connection file to store itself.

Here are the steps:

Create Directory

We create a directory for the destination of your database connection file.

[root@localhost www]# mkdir /var/www/db
[root@localhost www]# ls -l
drwxr-xr-x.  2 root root 4096 Dec 28 14:54 db

Move File

The new location of this file will be /var/www/db/

[root@localhost www]# mv /var/www/html/comm/ /var/www/db/

Change Path in Code

Change all the related code from:

require_once "";

into this:

$parent_dir = dirname($_SERVER['DOCUMENT_ROOT']);
$confidential_dir = $parent_dir . "/db";
require_once $confidential_dir . "/";

As you can see, we use dirname() to retrieve the parent directory path of DOCUMENT_ROOT, then get into our database directory for requiring the credential file.

Please note that, PHP allows you to use absolute paths to require files, which are more accurate than relative paths in many ways.

Leave a Reply

Your email address will not be published. Required fields are marked *