Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a config file in PHP

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

I have 3 ideas so far.

1-Use 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 be using the config in classes so I'm not sure which way would be the best or if there is a better way.

like image 208
Ali Akbar Azizi Avatar asked Feb 07 '13 13:02

Ali Akbar Azizi


People also ask

Where is the PHP config file?

user. ini file is the default configuration file for running applications that require PHP. It is used to control variables such as upload sizes, file timeouts, and resource limits. This file is located on your server in the /public_html folder.

What is PHP ini configuration file?

The php. ini file is a special file for PHP. It is where you declare changes to your PHP settings. The server is already configured with standard settings for PHP, which your site will use by default. Unless you need to change one or more settings, there is no need to create or modify a php.


2 Answers

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

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

And then:

$configs = include('config.php'); 
like image 57
Hugo Mota Avatar answered Sep 22 '22 22:09

Hugo Mota


Use an INI file is a flexible and powerful solution! PHP has a native function to handle it properly. For example, it is possible to create an INI file like this:

app.ini

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

So the only thing you need to do is call:

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

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

echo $ini['db_name'];     // mydatabase echo $ini['db_user'];     // myuser echo $ini['db_password']; // mypassword echo $ini['app_email'];   // [email protected] 

IMPORTANT: For security reasons the INI file must be in a non public folder

like image 32
Marcio Mazzucato Avatar answered Sep 21 '22 22:09

Marcio Mazzucato