HomePHP Page 4 - File And Directory Manipulation In PHP (part 2)
Configuring The System - PHP
Now that you know the basics of reading and writing files, this second segment of our tutorial on the PHP filesystem API takes you into deeper waters, showing you how to copy, delete and rename files; scan directories; work with uploaded files over HTTP; perform pattern matches on file names; and read and write to processes instead of files.
If what you're really after involves reading configuration variables in from a standard .INI file, you don't need to write custom code to parse the file and read in the variable-value pairs. Instead, just use PHP's parse_ini_file() function, which automatically takes care of this for you.
Consider the following sample .INI file,
[global]
printing = bsd
default case = lower
log file = /var/log/samba/log.%m
printcap name = /etc/printcap
max log size = 50
domain master = yes
dns proxy = no
[temp]
comment = Temporary file space
path = /tmp
read only = no
public = yes
create mask = 0777
force group = nobody
force user = nobody
and the PHP code to parse it:
<?php
// set file to read
$filename = "samba.ini";
// read INI file into array
$data = parse_ini_file($filename);
// print array
print_r($data);
?>
A quick glance at the output shows that PHP has, indeed, read the file, parsed its contents, and converted the variable-value pairs into an associative array.
The only problem with the approach, however, is that variables with the same name from different sections will override each other; if there are multiple configuration variables with the same name, the output array will always contain only the last value. In order to illustrate, look what happens when I add a new section to the sample file above which repeats some of the variables from a previous section:
[global]
printing = bsd
default case = lower
log file = /var/log/samba/log.%m
printcap name = /etc/printcap
max log size = 50
domain master = yes
dns proxy = no
[temp]
comment = Temporary file space
path = /tmp
read only = no
public = yes
create mask = 0777
force group = nobody
force user = nobody
As you can see, some of the variable-value pairs (from the "temp" section of the file) have been lost. PHP offers a solution to this problem by allowing a second, optional argument to parse_ini_file() - a Boolean indicating whether the namespaces of the various sections should be respected. When I add that to the script above,
<?php
// set file to read
$filename = "samba.ini";
// read INI file into array
// process each section separately
$data = parse_ini_file($filename, true);
With the addition of the second argument to parse_ini_file(), PHP now creates a nested array, with the outer array referencing the sections, and each inner one referencing the variables in each section.