Skip to content
Advertisement

How to prevent including database config.php from another client?

We have this config.php file:

<?php
$host = "host";
$dbname = "db";
$user = "user";
$pass = "pass";
        try {
        $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch(PDOException $e) {
        die("Error");
        }
?>

And this structure

/www/
    index.php
    config.php

The index file is accessable via www.example.com/index.php, but the config.php file too (via www.example.com/config.php).

Can others just include www.example.com/config.php in there php files and execute code with my $conn? How to prevent this?

Advertisement

Answer

It’s true that if you leave files in the web root, the web server will execute them when a matching request URI comes through.

However, do understand that the source code is not (normally) viewable by clients. For example, when someone makes a request for /index.php, they don’t see the PHP source code. They only see its output. Likewise, if someone were to make a request for /config.php, given the example code your question they should get nothing but an empty response. So, to answer your question…

Can others just include www.example.com/config.php in there php files and execute code with my $conn?

No, they cannot.

To execute code, they need to be running code on your server.

Now, it’s still a good practice to get your config.php and any other includes out of the web root. The reason for that is to prevent exposure of code in the event PHP gets disabled on your web server. It’s not too uncommon to try to upgrade your web server or something, break the config, accidentally disable PHP on a live server, and now everyone can see all your source code. If that source code isn’t in the web root, there’s nothing they can request.

Additionally, there are often more open permissions on files within your web root. So, it’s just a good practice to keep things out of there when you can… but not directly for the reason you were concerned about.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement