Restrict PHP database access

Chances are that most if not all of your scripts need database access to operate, which gives you two options: write database connection code into each of your scripts, or write it into just one script and link all your pages to that one. It is easy to place files outside of your public web directory, which means it is much easier to place all connection code into one file then place it in a secure location. If you place your connection code into each file, you are increasing the likelihood of your connection details getting out - all it would take is one page to be hacked.

There is, however, a third option that can sometimes be better: placing your connection details inside your php.ini file. If you do not supply connection details to mysqli_connect(), PHP will use the values set in your php.ini file, which means you do not need to store your username and password information in your scripts any more. At first this might sound perfect, but it has major security implications of its own:

  • Anyone with access to your php.ini can read the values direct from the file

  • Anyone with the ability to put scripts on your server can use the ini_get() function to read the value from your php.ini file

If you firmly believe you are safe from these two, go ahead and use your php.ini file


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Denial of service >>

Previous chapter: Restrict general database access

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.