Where to store MySQL credentials in PHP scripts?

2019-01-20 13:00发布

问题:

I know I need to store my login information outside of my web root in case Apache is cracked, but I am unsure of what my 'web root' is, where to store my login information, and how to access them from PHP.

Could someone explain?

回答1:

Your web root, which is $_SERVER['DOCUMENT_ROOT'] in PHP, is the folder on your filesystem that your webserver (in this case, Apache) points to for a particular host.

For example, if you put this code in your index.php file and visit your domain name (or subdomain name), it will tell you your web root.

    <?php
    header("Content-Type: text/plain;charset=UTF-8");
    die($_SERVER['DOCUMENT_ROOT']);
    ?>

It should say something like, /home/some_user/public_html or /var/www. In this case, you want to create a path that is not inside of this directory.

For example: /home/some_user/config or /var/webconfig.

You do NOT want to store it in /home/some_user/public_html/config (notice the public_html) or /var/www/webconfig (notice this is a subfolder of /var/www)

The idea of storing data outside your web root is that an attacker cannot navigate to http://yoursite.com/config/mysql.txt and obtain your passwords. LFI and directory traversal attacks are not in the scope of this initiative.

You also should not check any sensitive information (database credentials, encryption keys, etc.) into version control. Ever.

How to access them from PHP?

That depends how your configuration is encoded.

<?php
$config = parse_ini_file('/home/some_user/config/mysql.ini');
// OR
$config = json_decode('/home/some_user/config/mysql.json');
// OR
require_once '/home/some_user/config/mysql_config.php';
?>


回答2:

Typically, I use a folder outside my webroot for application code (functions, etc..) including the mysql connecting php. I create a folder (/home/user/application or similar) and make a mysqlconnect.php file there with the code to connect to mysql or error out. Then, make sure that the path (/home/user/application/ is in the include directory, and at the top of index.php(index.html), include:

<?php
include('/home/user/application/mysqlconnect.php');

?>

It is also good advise to store any password obfuscation code in this way, so that your method, dynamic salt, and static salt can not be compromised in a similar way.

Hope that helps