- Read Configuration Setting from php.ini
- Php configuration file settings
- Reading and Writing Configuration Files
- Reading and Writing Configuration Files
- — Additional info —
- What’s the best way ro read from a config file in PHP
- How to import a config.php file in a php script [duplicate]
- Load website configuration from JSON or PHP file?
Read Configuration Setting from php.ini
In any application development, design of configuration files are very important, because there are different server connection reference are used in several times in application coding, so when we deploy application from one environment to another environment (like dev to staging server, then production server), all the configuration values will change.
Therefore, to make the change process easy, we keep all type of configuration values in one place. Here you learn how to read configuration setting in php application.
Php configuration file settings
Php.ini file contain system configuration related information in plain text format, the file reside in root of php folder.
Here are some system configuration information written in php.ini file
[Syslog] define_syslog_variables=Off [Session] define_syslog_variables=Off [Date] date.timezone=Europe/Berlin [MySQL] mysql.allow_local_infile=On mysql.allow_persistent=On mysql.cache_size=2000 mysql.max_persistent=-1 mysql.max_link=-1 mysql.default_port=3306 mysql.default_socket="MySQL" mysql.connect_timeout=3 mysql.trace_mode=Off [Sybase-CT] sybct.allow_persistent=On sybct.max_persistent=-1 sybct.max_links=-1 sybct.min_server_severity=10 sybct.min_client_severity=10 [MSSQL] mssql.allow_persistent=On mssql.max_persistent=-1 mssql.max_links=-1 mssql.min_error_severity=10 mssql.min_message_severity=10 mssql.compatability_mode=Off mssql.secure_connection=Off
We can store any application configuration related information like database details, SMTP details, or any other template related information.
This is how you can store application related information in httpd.conf file
php_value mysql.default.user myusername php_value mysql.default.password mypassword php_value mysql.default.host myserver
Now to retrieve information in php code we can use the same keys
$db = mysqli_connect(ini_get("mysql.default.user"), ini_get("mysql.default.password"), ini_get("mysql.default.host"));
We can also store all configuration related information in config.ini file.
[database] servername = myservername username = mydbuser password = mypassword dbname = myDBName
Now in php code we can add the file reference, then retrieve the configuration related information using right keys.
Here is how you can read configuration information in php from config.ini file.
$config = parse_ini_file('../fodlername/config.ini'); $connection = mysqli_connect($config['servername'],$config['username'],$config['password'],$config['dbname']);
Reading and Writing Configuration Files
Suggestion It’s good to build configs so you can load different config files for different environments (prod, staging, local, testing etc). it is one of the faster method to load configuration files.
Reading and Writing Configuration Files
I’m writing a small script which generates some configuration for devices. I want to have separate file, where I’m storing configuration, and change some strings during printing the content of the configuration to the browser. How can I replace string in a line of the file with a variable from $_POST[‘somevariable’]?
— Additional info —
I have several types of devices. I want to have separate file with configuration template for each type of device. If someone want to change configuration of some type device they will change that file not php file. But in order to use this template in php I have to replace some string in that file before printing out to web page, e.g.: sys info hostname %host_name% sys info location %location% ip set %ip% the strings inbetween %% (could be any other) characters should be replaced with $_POST[«host_name»], $_POST[«location»], $_POST[«ip»] etc. All these params gotten from the posted form.
It is advisable to use a structured file format of some sort for this purpose.
Consider using CSV, Ini, XML, JSON or YAML and use appropriate APIs to read and write them.
Another alternative would be to store the configuration in an array and then either use serialize/unserialize or use var_export/include to use it.
class MyConfig < public static function read($filename) < $config = include $filename; return $config; >public static function write($filename, array $config) < $config = var_export($config, true); file_put_contents($filename, ">
You could use the class like this:
MyConfig::write('conf1.txt', array( 'setting_1' => 'foo' )); $config = MyConfig::read('conf1.txt'); $config['setting_1'] = 'bar'; $config['setting_2'] = 'baz'; MyConfig::write('conf1.txt', $config);
Use SQLite. You can then query for specific data, and still have a local file. FYI — PDO quote automatically adds single quotes around a value.
$Filename = "MyDB.db"; try < $SQLHandle = new PDO("sqlite:".$Filename); >catch(PDOException $e) < echo $e->getMessage()." :: ".$Filename; > $SQLHandle->exec("CREATE TABLE IF NOT EXISTS MyTable (ID INTEGER PRIMARY KEY, MyColumn TEXT)"); $SQLHandle->beginTransaction(); $SQLHandle->exec("INSERT INTO MyTable (MyColumn) VALUES (".$SQLHandle->quote("MyValue").")"); $SQLHandle->exec("INSERT INTO MyTable (MyColumn) VALUES (".$SQLHandle->quote("MyValue 2").")"); $SQLHandle->commit(); $Iterator = $SQLHandle->query("SELECT * FROM MyTable ORDER BY MyColumn ASC"); unset($SQLHandle); foreach($Iterator as $Row)
If you don’t follow his advice you can do something like this:
$file = file_get_contents('./conf.tpl'); $file = str_replace('%server%', 'localhost', $file); file_put_contents('./conf.txt', $file);
How to get PHP to be able to read system environment, You need to read the environment variables from the correct location. PHP creates a super global variable for this: $_ENV So you can access a single variable by accessing a certain element from that variable, which holds an array: echo $_ENV [‘SOME_SERVER_SETTING’];
What’s the best way ro read from a config file in PHP
I know this can be a lot subjective. I always worked with frameworks so I am a bit lost when I have to work on something from scratch.
I want to make a class that reads values from a config file. I’d prefer to use a php array as a config file rather than a .ini one.
What’s the best approach for that? using require_once inside a method looks to me a bit odd.
what I would like to do is a class that reads a config file and exposes this values as properties.
thanks for your suggestion
To read any ini file in to array:
$ini_array = parse_ini_file("sample.ini"); print_r($ini_array);
To use an array through require(require_once):
"mysql", "folder" => "cache"]; // index.php $config = require_once("config.php");
In OOP it might look something like that. Do not have any validations!
'mysql']; // Config.php class Config < public static function getInstance($configFile) < if (self::$instance == null) < // check that file exists. $ext = strtolower(substr($configFile, -3)); if ($ext === "php") < $data = require($configFile); >elseif ($ext) === "ini") < $data = parse_ini_file("sample.ini"); >else < throw new \Exception('Can nod read config file'); >self::$instance = new \ArrayObject($data, \ArrayObject::ARRAY_AS_PROPS); //or //self::$instance = (object) $data; > return self::$instance; > private static $instance; > // Usage $config = Config::getInstance('path/to/config/file.php'); echo $config->db;
Most php config files use constants;
define("SITE_NAME", "My Test Site");
How to import a config.php file in a php script, since it contains the same array as you returned in the config file. Suggestion. It’s good to build configs so you can load different config files for different environments (prod, staging, local, testing etc). So would suggest that you pass the path to the config file to the constructor. Then you can pass different files for …
How to import a config.php file in a php script [duplicate]
i try to read a config.php into a php class but can’t do it.
I want to load the config only when I really need it and not just import it at the beginning of the program
I searched the internet a lot, but found no explanation.
I’ll show you my class, where I read the Config:
mailConfigs = require __DIR__ . '/../../Config/MailConfiguration.php'; > /** * @return mixed */ public function getMailConfig() < return $this->mailConfigs; > >
My index file looks like this:
getMailConfig(); var_dump($mailConfiguration);
Unfortunately, this code only gives me errors that it could not find the config.
I then thought that the config dn can only be used in the Mailer.php class, but even then, I only get error messages that he can’t find the config:
mailConfigs = require __DIR__ . '/../../Config/MailConfiguration.php'; > /** * @return mixed */ public function getMailConfig() < $this->mailConfigs; var_dump($mailConfig); > >
btw. my config looks like this:
'wk@someSender.com', 'mailSubject' => 'XXX', 'maxConnections' => 400, 'maxTime' => 600, 'csv' => 'mailaccounts.csv', ];
Can someone help me and explain how I can correctly access the array in the config in oop without reading it globally?
The problem with the code is that you’re not actually returning the config in your MailConfiguration.php . You define it as a variable, which you never use in the constructor.
Instead of storing the config array in a variable in your config file, do:
return [ 'mailSender' => 'wk@someSender.com', 'mailSubject' => 'XXX', 'maxConnections' => 400, 'maxTime' => 600, 'csv' => 'mailaccounts.csv', ];
Now the config array will be loaded into $this->mailConfigs in your constructor.
Then, when you want to use it, just do:
public function getMailConfig() < return $this->mailConfigs; >
since it contains the same array as you returned in the config file.
Suggestion
It’s good to build configs so you can load different config files for different environments (prod, staging, local, testing etc). So would suggest that you pass the path to the config file to the constructor. Then you can pass different files for different environments. Example:
public function __construct($configFile) < $this->mailConfigs = require $configFile; >
and when you instantiate the class:
$mailer = new Mailer(__DIR__ . '/../../Config/MailConfiguration.php');
Then you can make the file you’re passing in conditional on the current environment.
An alternative way would be to save the configuration in a different format, i.e. to serialize it and deserialize it if needed. One format to use would be the JSON format.
config = file_get_contents('config.php'); $this->config = json_decode($this->config,true); echo $this->config['a']; //Test Config echo $this->config['b']; //Test B > > ?>
PHP: reading config.ini to array with file(), when I read the file with file(), it creates this array [0] => title = myTitle; [1] => otherTitle = myOtherTitle; and what I want the array to look like is [title] => myTitle; [otherTitle] => myOtherTitle; Am I using the wrong approach her? Should i just read the entire config into a sting and explode it from there?
Load website configuration from JSON or PHP file?
I’ve stored some website configuration data in a config.json file, with things like database connection parameters and routes. Something like this:
And the content is loaded with:
$config = json_decode(file_get_contents('config'), true);
However, inspecting some frameworks, I see direct usage of PHP scripts for configuration storage:
array( . ), 'test' => array( . ), 'development' => array( . ) );
Which approach is the best?
There are several advantages to using the config.php approach:
- The PHP compiler will tell you quickly if you have a syntax error in the config.php file when it gets loaded, whereas you would have to wait until you parse the JSON file to pick up any errors
- The PHP file will load faster than parsing the JSON file for the 2nd and subsequent page loads because the script will be cached by the web server (if cacheing is supported & enabled).
- There is less chance of security breach. As Michael Berkowski pointed out in his comment, if you don’t store your JSON file outside the document root or configure the web server settings properly, web clients will be able to download your JSON file and get your database username & password and gain direct access to your database. By contrast, if the web server is configured properly to process *.php files via the PHP script engine, a client cannot directly download config.php even if it resides under the document root directory.
Not sure there are really any advantages to using JSON rather than config.php other than if you had multiple applications written in different languages (perl, python, and php for example) that all needed access to the same shared configuration information. There may be other advantages to JSON, but none come to mind at the moment.
It is generally faster to load from a PHP config file, plus it also supports more features, such as closures and byte code caching (if enabled).
Just a note — PHP has a special function for fast loading .ini files that can parse your configuration file
as mentioned in : PHP parse_ini_file() performance?
it is one of the faster method to load configuration files.
Oop — load config.php with in a class, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more