Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store configuration variables in PHP?

Tags:

I need to store a bunch of configuration information in PHP.

I have considered the following....

// Doesn't seem right. $mysqlPass = 'password';   // Seems slightly better. $config = array(      'mysql_pass' => 'password' );  // Seems dangerous having this data accessible by anything. but it can't be // changed via this method. define('MYSQL_PASSWORD', 'password');   // Don't know if this is such a good idea. class Config {     const static MYSQL_PASSWORD = 'password'; }      

This is all I have thought of so far. I intend to import this configuration information into my application with require /config.inc.php.

What works for you with regard to storing configuration data, and what are best practices concerning this?

like image 417
alex Avatar asked Feb 27 '09 03:02

alex


People also ask

Where is config PHP stored?

I usually place database settings on config. php and all the dynamic settings on a database. All settings that don't change much are usually good to be placed to config file.

What is the way to include the file config PHP?

Copy the below code to include the 'config. php' file and get a print the name of the database and username. include ( 'config. php' );

How can I access config variable in PHP?

php include("config. php"); at the top of the PHP file you want to access it in. You will then be able to access the config variables form that PHP file it is declared in.

What is the order of variables in PHP?

Rules for PHP variables: A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number.


1 Answers

I've always gone with option #2 and just ensure that no one but the owner has ANY sort of access to it. It's the most popular method among PHP applications like Joomla, vBulletin, Gallery, and numerous others.

First method is too messy to me (readability) and the third is WAY too dangerous to do. I've never thought about the Class method, so someone else can provide their input on that one. But I guess it's fine so long as the right access is used on the class' usage.


Example..

define('EXAMPLE1', "test1"); // scenario 1 $example2 = "test2"; // scenario 2  function DealWithUserInput($input) {    return eval($input); } 

Now this example of code is really dumb, but just an example. Consider what could be returned by the function depending on which scenario the user could try to use in their input.

Scenario 2 would only cause an issue if you made it a global within the function. Otherwise it's out of scope and unreachable.

like image 60
William Holroyd Avatar answered Sep 24 '22 02:09

William Holroyd