Home >Backend Development >PHP Tutorial >How to Read, Write, and Modify INI Files in PHP?
Reading and Writing INI Files in PHP
Parse_ini_file is commonly used to read INI files in PHP. To read an INI file:
<code class="php">$ini_array = parse_ini_file("sample.ini"); print_r($ini_array);</code>
To access specific values:
<code class="php">echo $ini_array['lu_link']; echo $ini_array['footerbg'];</code>
Writing back to the INI file requires a custom function:
<code class="php">function write_php_ini($array, $file) { $res = []; foreach ($array as $key => $val) { if (is_array($val)) { $res[] = "[$key]"; foreach ($val as $skey => $sval) { $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"'); } } else { $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"'); } } safefilerewrite($file, implode("\r\n", $res)); }</code>
Safefilerewrite ensures exclusive file access using flock:
<code class="php">function safefilerewrite($fileName, $dataToSave) { if ($fp = fopen($fileName, 'w')) { $startTime = microtime(TRUE); do { $canWrite = flock($fp, LOCK_EX); if (!$canWrite) { usleep(round(rand(0, 100) * 1000)); } } while ((!$canWrite) && ((microtime(TRUE) - $startTime) < 5)); if ($canWrite) { fwrite($fp, $dataToSave); flock($fp, LOCK_UN); } fclose($fp); } }</code>
Example Usage:
<code class="php">$ini_array = parse_ini_file("sample.ini"); $ini_array['lu_link'] = '#F00'; $ini_array['footerbg'] = '#FFF'; write_php_ini($ini_array, "sample.ini");</code>
The above is the detailed content of How to Read, Write, and Modify INI Files in PHP?. For more information, please follow other related articles on the PHP Chinese website!