Home > Backend Development > PHP Tutorial > How to Read, Write, and Modify INI Files in PHP?

How to Read, Write, and Modify INI Files in PHP?

Mary-Kate Olsen
Release: 2024-10-28 20:16:31
Original
977 people have browsed it

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>
Copy after login

To access specific values:

<code class="php">echo $ini_array['lu_link'];
echo $ini_array['footerbg'];</code>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template