Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store MySQL credentials in PHP scripts?

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?

like image 358
shane Avatar asked Dec 26 '22 06:12

shane


1 Answers

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';
?>
like image 73
Scott Arciszewski Avatar answered Dec 27 '22 19:12

Scott Arciszewski