Oliver Bayes-Shelton
Oliver Bayes-Shelton

Reputation: 6292

safest place to store php values for msql_connect?

Were is the safest place to store my values which will be used in mysql_connect also what is the safest way to call these variable would be better using a require , include or something else ?

thanks :)

Upvotes: 4

Views: 264

Answers (2)

Marius
Marius

Reputation: 58911

This is what I usually do:

  • Set up the project so the website is a subfolder of the project. That way you can have all PHP classes and config files outside the web root folder.
  • Have a config.php file with an array of Database credentials. For example:
$databases = array(
      "read" => array("host" => "127.0.0.1", 
                      "user" => "read", 
                      "pword"=> "secret",
                      "dbase"=> "projectName"));
  • Extend the PDO class (or create a new class) called Database that has a constructor taking one argument.
class Database extends PDO{
  function __construct($database){
    global $databases;
    $db = $databases[$database];
    parent::__construct("mysql:dbname=".$db['dbase'].";host=".$db['host'], 
                        $db['user'], $db['pword']);
  }
}

Now you can pass the array key to one of the database credentials as an argument to the Database class constructor, and then it will sign in with those details. This means that you can have several users to access the database (one for reading, and one for writing).

Upvotes: 1

Pekka
Pekka

Reputation: 449385

The best place to store it IMO is in a PHP file (whether you use require or include to fetch it doesn't matter) outside the web root, i.e. not directly accessible in the browser.

<?php

  $db_server = "xyz";
  $db_user = "def";
  $db_password = "abc";

?>

If there is no access outside the web root

@Yacoby wrote this down in his answer. He deleted it since, but it definitely deserves mention.

There are foolish hosting providers who don't allow access outside the web root. In that case, you put the config file in a directory in your web site and protect it using a .htaccess file containing Deny from All. This works on most hosting packacges. Make sure you test it though, you should get a 403 Forbidden when trying to access that file.

Upvotes: 7

Related Questions