im an overall total beginner in web programming. Im trying to produce a simple website that's reading through data from the SQL Database. In the beginning i simply authored my database password and login into the php code:

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

This clearly is not makes sense! What exactly is really a (much) more "secure" method of doing this? I just read about putting the php code right into a seperate file, meaning not in to the primary php document from the website, after which restricting the use of that file. Maybe with a .htaccess file. Is what you want?

The config.php file and also the .htaccess is really a classic/good approach to take. It's the actual way it is generally completed with Content management systems or frameworks.

As pointed by JohnP, you may also keep config.php outdoors from the public directory, this means that it cannot be utilized via HTTP. This is just a little better for security (if you do not get it wrong together with your .htaccess, there's forget about risks).

File structure example :

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

This way, http://www.your-site.com/ indicates public/, so there is no means to access the config. But this solution suggests that you could alter the root web directory (or that it's already like this).

Finally, you should know to create this file readable and writeable through the Apache user only, not everybody (unix file access privileges), to ensure that if a person access you server through another user, he can't browse the file.

You normally put this inside a configuration file and also you access the configuration values via PHP.

Often a project is organized so that the application code as well as your configuration code is outdoors your webroot and just your public assets (index.php, images, scripts or any other assets) can be found via immediate access.