Protect files with sensitive data in PHP


In PHP we can use files to store sensitive data, but those files must have certain levels of protection.

We are going to take the example of a file that stores our login credentials to the database.

To save this important information I have created a db.php.ini file that contains the following:

<?php return; ?>
; credenciales

This file applies several levels of security:

  • It is in a folder outside the root or public_html , so it can not be accessed through the browser
  • You are in a hidden folder .credenciales
  • It has this at the beginning <?php return; ?> so that, if by some chance it is accessed by URL, it does not show anything.
  • The reading of that file, when connecting to the database, is done like this:

    private function Connect()
        /* Leer credenciales desde el  archivo ini */
            $this->credenciales = parse_ini_file(".credentials/db.php.ini");
            $dsn = 'mysql:dbname=' . $this->credenciales["dbnombre"] . 
                   ';host=' . $this->credenciales["host"] . '';
            $pwd = $this->credenciales["clave"];
            $usr = $this->credenciales["usuario"];
    // ... más código

    The question

    Are there other measures that could be taken to give this file more security? What would those measures be?

    asked by A. Cedano 07.11.2017 в 00:46

    1 answer


    When working with sensitive files (credentials, configuration files, database connections) in a web server it is advisable that they are always located outside the public directory, so that they can not be accessed directly. .

    But is it enough to put the files in a non-public directory?

    Obviously not, we must take into account some recommendations to limit the access of these files by other means.

    • Set only the necessary permissions.
    • Avoid using PHP functions (or other languages) that can execute code or commands (eg: eval, exec ...) and if necessary be very careful.
    • Avoid using default routes to administration panels (example:
    • Avoid or restrict ftp access in production and / or user by default or weak passwords.

    This does not guarantee 100% security because a server can be compromised due to other factors.

    answered by 23.11.2017 в 15:11