The ini File
The ini(initialization) file has come to be a pseudo standard among application developers for initializing data variables.Most applications that use an ini file for configuration use the PHP parse_ini_file() function to get values from the ini file. Many classes and abstractions have been written to provide a Object Oriented approach, but the core remains the single PHP function to gain access to the values within.
The simple syntax within the ini file makes it simple to edit and is easy to read. The reason it has been around so long is due to this simplicity. Here is an example of an ini file. Create file called "config.ini"
; ; This is a comment ; [database] db_username = username db_password = password db_host = localhost db_port = 1234 [mail] mail_username = username mail_password = password mail_host = mail.example.com [blog] blog_title = "My Blog" blog_moderate = 1 blog_images = 1
To parse the example config.ini file use PHP parse_ini_file() function in your php file.
<?php
/*** turn on errors ***/
error_reporting(E_ALL);
/*** parse the ini file ***/
$config = parse_ini_file("config.ini", 1);
/*** print the array ***/
print_r($config);?>
This simple script above reads the ini file int a multi-dimensional array for easy retrieval. The array looks like this.
Array ( [database] => Array ( [db_username] => username [db_password] => password [db_host] => localhost [db_port] => 1234 ) [mail] => Array ( [mail_username] => username [mail_password] => password [mail_host] => mail.example.com ) [blog] => Array ( [blog_title] => My Blog [blog_moderate] => 1 [blog_images] => 1 ) )
To retrieve a single value from the array is now a simple matter of reading the array as with any PHP array. In the following script, a single value is retrieved from the ini file, and a timer is added to see how long it takes.
<?php
/*** turn on errors ***/
error_reporting(E_ALL);
/*** start a timer ***/
$start = microtime(true);
/*** parse the ini file ***/
$config = parse_ini_file("config.ini", 1);
/*** get the database user name ***/
echo $config['database']['db_username']."\n";
/*** end timer ***/
$end = microtime(true);
/*** show duration ***/
echo round( $end - $start, 6) . "\n";?>
The above script echos the database db_username configuration option and calculates the time in seconds, rounded to six decimal places. The results from this test averaged around 0.000421
username 0.000425
No comments:
Post a Comment