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

How to Read and Write Values in PHP INI Files?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 00:48:02312browse

How to Read and Write Values in PHP INI Files?

Editing and Reading PHP INI File Values

For reading INI file values in PHP, you can utilize the parse_ini_file function. Simply call it with the INI file path as an argument. For instance:

<code class="php">$ini_array = parse_ini_file("sample.ini");</code>

This will store the values in an array where the INI section names represent the keys and the values are stored as array elements. To access the value for "lu_link" or "footerbg", you can use:

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

Writing back to the INI file is not as straightforward as reading. However, one efficient method involves using the write_php_ini 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>

In this function, safefilerewrite is used to safely rewrite the file to avoid overwriting issues. It utilizes a lock mechanism to prevent collisions and ensure data integrity.

To use this function, you simply pass an array with the desired INI values and the INI file path as arguments:

<code class="php">$ini_values = ['lu_link' => '#EF32AB', 'footerbg' => '#000000'];
write_php_ini($ini_values, "sample.ini");</code>

The above is the detailed content of How to Read and Write Values in PHP INI Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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