Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Database Login Information in PHP Code

im a total beginner in web programming. Im trying to create a simple website that is reading data from a SQL Database. At first i just wrote my database password and login directly into the php code:

<?php
$username = "login";
$password = "pw";
mysql_connect("server", $username, $password);
...
?>

This obviously isn't a very good idea! So what is a (much) more "secure" way to do this? I read about putting the php code into a seperate file, meaning not into the main php document of the website, and then restricting the access to that file. Maybe by a .htaccess file. Is this the way to go?

like image 252
gaussd Avatar asked May 11 '11 10:05

gaussd


1 Answers

The config.php file and the .htaccess is a classic/good way to go. It's the way it is usually done with CMS or frameworks.

As pointed by JohnP, you can also store the config.php outside of the public directory, that means that it can't be accessed via HTTP. This is only a little better for security (if you don't make a mistake with your .htaccess, there is no more risks).

File structure example :

  • config/ -> configuration files
  • lib/ -> libraries and utils PHP files
  • public/ -> all you public pages/files/images...

That way, http://www.your-site.com/ points to public/, so there's no way to access the config. But this solution implies that you can change the root web directory (or that it is already like that).

Finally, you have to remember to set this file readable and writeable by the Apache user only, not everyone (unix file access rights), so that if someone gain access to you server through another user, he can't read the file.

like image 83
Matthieu Napoli Avatar answered Oct 03 '22 14:10

Matthieu Napoli