How to securely connect to a database with PHP?

Your approach looks good.

  • You are storing the credentials in a separate configuration file instead of having them written inline in the source code. This makes it safe when sharing the code with others and protects the credentials in case a misconfiguration lets the plain PHP code be printed out (which happens quite often).

  • The config file is outside the public document root, therefore it cannot be directly accessed by a user of the web application, unless there is another vulnerability (e.g. a directory traversal flaw).

  • In any case you should avoid running the server as root. Otherwise the permission model is worthless, since root can read and write to any file.

Note that you don't have to deal with parsing the credentials in your code at all - you can instead specify them as PHP runtime settings in the server configuration, as explained here.

Also see: