Creating a configuration file in PHP

I want to create a configuration file for my PHP project, but I'm not sure which is the best way to do this.

I have 2 ideas so far.

1-Use a variable

$config['hostname'] = "localhost"; $config['dbuser'] = "dbuser"; $config['dbpassword'] = "dbpassword"; $config['dbname'] = "dbname"; $config['sitetitle'] = "sitetitle"; 

2-Use Const

 define('DB_NAME', 'test'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); define('TITLE', 'sitetitle'); 

3-Use database

I will use the configuration in classes, so I'm not sure which way would be better, or if there is a better way.

+84
php configuration-files
Feb 07 '13 at
source share
10 answers

One simple but elegant way is to create a config.php (or whatever you call) that simply returns an array:

 <?php return array( 'host' => 'localhost', 'username' => 'root', ); ?> 

And then:

 $configs = include('config.php'); 
+182
Feb 07 '13 at 13:44
source share

Using an INI file is a flexible and elegant solution! PHP has a built-in function for proper handling. For example, you can create an INI file as follows:

 [database] db_name = mydatabase db_user = myuser db_password = mypassword [application] app_email = mailer@myapp.com app_url = myapp.com 

So the only thing you need to do is call:

 $ini = parse_ini_file('app.ini'); 

Then you can easily access the definitions using the $ini array.

 echo $ini['db_name']; // mydatabase echo $ini['db_user']; // myuser echo $ini['app_name']; // mypassword 

IMPORTANT: For security reasons, the .ini file must be located in a public folder.

+57
Dec 07 '15 at 14:03
source share

I am using a small evolution of @hugo_leonardo's solution:

 <?php return (object) array( 'host' => 'localhost', 'username' => 'root', 'pass' => 'password', 'database' => 'db' ); ?> 

This allows you to use the object syntax when php is included: $configs->host instead of $configs['host'] .

In addition, if your application has settings on the client side (for example, for an Angular application), you can have this config.php containing all your configs (centralized in one file instead of one for JavaScript and one for PHP). Then the trick was to have another PHP file in which echo was only information about the client side (in order not to show the information that you do not want to show as a connection string to the database). Call say get_app_info.php :

 <?php $configs = include('config.php'); echo json_encode($configs->app_info); ?> 

The above assumption is that your config.php contains the app_info parameter:

 <?php return (object) array( 'host' => 'localhost', 'username' => 'root', 'pass' => 'password', 'database' => 'db', 'app_info' => array( 'appName'=>"App Name", 'appURL'=> "http://yourURL/#/" ) ); ?> 

Thus, information about your database remains on the server side, but your application information is available from your JavaScript, for example, the call type $http.get('get_app_info.php').then(...); .

+23
Oct. 16 '16 at 6:08
source share

I am quite surprised at the accepted answer here, and the number of its elevations. With the exception of Marcio Mazzukato's answer, there is no discussion of the relative strengths / weaknesses of any of several approaches.

The options that I see are as follows:

File-based mechanisms

This requires your code to look in certain places to find the ini file. This is a difficult problem to solve, which always arises in large PHP applications. However, you will likely have to solve the problem in order to find PHP code that is included / reused at runtime.

General approaches to this are to always use relative directories or look up from the current directory to find a file exclusively named in the application’s base directory.

Typical file formats used for configuration files are PHP code, ini-formatted files, JSON, XML, YAML, and serialized PHP

Php code

This provides tremendous flexibility for representing various data structures and (provided that it is processed using include or require), the analyzed code will be accessible from the operation code cache, which gives an advantage in performance.

include_path provides a means to abstract away potential file locations without relying on additional code.

On the other hand, one of the main reasons for sharing configuration from code is separation of duties. It provides a route for entering additional code at run time.

If the configuration is created from a tool, it may be possible to check the data in the tool, but there is no standard function to delete data for embedding in PHP code, as it exists for HTML, URLs, MySQL statements, shell commands ....

Serialized data This is relatively effective for small configuration volumes (up to 200 units) and allows you to use any PHP data structure. To create / analyze a data file, very little code is required (so you can instead spend your efforts on writing the file only with the appropriate authorization).

Resetting the contents written to the file is processed automatically.

Since you can serialize objects, this makes it possible to call the code simply by reading the configuration file (magic method __wakeup).

Structured file

Saving as an INI file, as suggested by Marcel or JSON or XML, also provides a simple api to map the file to the PHP data structure (and, with the exception of XML, to delete the data and create the file) while eliminating the vulnerability of calling code using PHP serialized data .

It will have similar performance characteristics with serialized data.

Database repository

This is best considered when you have a huge configuration, but selectively what is needed for the current task - I was surprised to find that about 150 data items had faster data retrieval from local MySQL than for non-serialization of a data file.

OTOH is not the best place to store credentials that you need to connect to your database.

Execution conditions

You can set values ​​in runtime . PHP is working.

This removes any requirement for the PHP code to look in a specific location for configuration. OTOH does not scale well for large amounts of data and is difficult to change everywhere at runtime.

On the client

One place that I did not mention for storing configuration data is on the client. Again, network overhead means that it does not scale well for large configuration volumes. And since the end user has control over the data, it must be stored in a format in which any interference can be detected (i.e. with a cryptographic signature), and should not contain any information that is compromised by its disclosure (i.e. reversibly encrypted).

Conversely, it has many advantages for storing confidential information that belongs to the end user - if you do not store it on the server, it cannot be stolen.

Network directories Another interesting place to store configuration information is in DNS / LDAP. This will work for a small number of small pieces of information, but you do not need to adhere to the 1st normal form - consider, for example, SPF ,

The subsystem supports caching, replication and distribution. Therefore, it works well for very large infrastructures.

Version Control Systems

Configuration, such as code, must be versioned and versioned - so getting the configuration directly from your VC system is a viable solution. But often this is associated with significant performance overheads, so caching may be appropriate.

+19
Jul 13 '17 at 16:57
source share

Good - it would be difficult to store database configuration data in the database - right?

But in fact, this is a pretty stubborn question, because any style really works, and it all depends on preferences. Personally, I would choose a configuration variable, not constants - in general, because I don’t like things in the global space, if necessary. None of my codebase functions should be able to easily access my database password (other than my database connection logic), so I would use it there and then probably destroy it.

Edit : to answer your comment - none of the parsing mechanisms would be the fastest (ini, json, etc.), but they are also not part of your application, you need to focus on optimization, since the difference in speed will be insignificant on such small files.

+6
Feb 07 '13 at
source share

Define will make a constant available everywhere in your class without having to use a global one, while a variable requires a global class, I would use DEFINE. but then again, if the db parameters should change during program execution, you might want to stick with the variable.

+2
Feb 07 '13 at
source share

If you think that for some reason you will use more than 1 dB, go to the variable, because you can change one parameter to switch to a completely different db. That is, for testing, autobackup, etc.

+2
Feb 07 '13 at 13:44
source share

You can create static properties of a class of a configuration class

 class Config { static $dbHost = 'localhost'; static $dbUsername = 'user'; static $dbPassword = 'pass'; } 

then you can just use it:

 Config::$dbHost 



Sometimes in my projects I use the SINGLETON design pattern to access configuration data. It is very convenient to use.

Why?

For example, you have 2 data sources in your project. And you can choose which witch is included.

  • MySQL
  • Json

Somewhere in the configuration file you select:

 $dataSource = 'mysql' // or 'json' 

When you change the original whole shoud application to a new data source, work fine and do not need to change the code.

Example:

Config:

 class Config { // .... static $dataSource = 'mysql'; / ..... } 

Singleton Class:

 class AppConfig { private static $instance; private $dataSource; private function __construct() { $this->init(); } private function init() { switch (Config::$dataSource) { case 'mysql': $this->dataSource = new StorageMysql(); break; case 'json': $this->dataSource = new StorageJson(); break; default: $this->dataSource = new StorageMysql(); } } public static function getInstance() { if (empty(self::$instance)) { self::$instance = new self(); } return self::$instance; } public function getDataSource() { return $this->dataSource; } } 

... and somewhere in your code (e.g. in some class):

 $container->getItemsLoader(AppConfig::getInstance()->getDataSource()) // getItemsLoader need Object of specific data source class by dependency injection 

We can get the AppConfig object from anywhere on the system and always get the same copy (thanks to the static one). The init () method of the class is called in the constructor, which guarantees only one execution. Checking Init () value config $ dataSource and creating a new object of a specific data source class. Now our script can get the object and work on it, not even knowing what specific implementation really exists.

+2
Oct 18 '17 at 11:31 on
source share

Usually I create a single conn.php file with my database connections. Then I include this file in all files that require database queries.

+1
Feb 07 '13 at
source share

Here is my way.

 <?php define('DEBUG',0); define('PRODUCTION',1); #development_mode : DEBUG / PRODUCTION $development_mode = PRODUCTION; #Website root path for links $app_path = 'http://192.168.0.234/dealer/'; #User interface files path $ui_path = 'ui/'; #Image gallery path $gallery_path = 'ui/gallery/'; $mysqlserver = "localhost"; $mysqluser = "root"; $mysqlpass = ""; $mysqldb = "dealer_plus"; 

? >

Any doubt please comment

0
Apr 13 '15 at 6:37
source share



All Articles