Skip to content

How To Hide Your Database Connection File

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

<?php
...
$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/db.inc, you can create a directory /var/www/db outside the document root for your database connection file to store itself. Here are the steps:

  1. Create a directory for the destination of your database connection file.
  2. [root@localhost www]# mkdir /var/www/db
    [root@localhost www]# ls -l
    ...
    drwxr-xr-x.  2 root root 4096 Dec 28 14:54 db
    ...
  3. Move the file to the new location
  4. The new location of this file will be /var/www/db/db.inc

    [root@localhost www]# mv /var/www/html/comm/db.inc /var/www/db/
  5. Change all the related code from:
  6. <?php
    require_once "db.inc";
    ...
    ?>
    Into:
    <?php
    $parent_dir = dirname($_SERVER['DOCUMENT_ROOT']);
    $confidential_dir = $parent_dir . "/db";
    require_once $confidential_dir . "/db.inc";
    ...
    ?>

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.