Home  >  Article  >  Backend Development  >  How to Read and Edit Values in PHP INI Files?

How to Read and Edit Values in PHP INI Files?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 02:29:02177browse

How to Read and Edit Values in PHP INI Files?

Edit and Read Values from PHP INI Files

It can be frustrating to search for the functionality to read and edit PHP INI files and not find it in the documentation. Here's how to accomplish these tasks:

Reading Values

To read the value for "lu_link" or "footerbg," use the parse_ini_file() function:

<code class="php">$ini_array = parse_ini_file("sample.ini");
echo $ini_array['lu_link']; // Output: #F8F8F8
echo $ini_array['footerbg']; // Output: #F8F8F8</code>

Writing Values

To update values, you can use 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));
}

function safefilerewrite($fileName, $dataToSave) {
    if ($fp = fopen($fileName, 'w')) {
        $startTime = microtime(TRUE);

        do {
            $canWrite = flock($fp, LOCK_EX);

            // Wait to avoid collision and CPU load
            if (!$canWrite) usleep(round(rand(0, 100) * 1000));
        } while ((!$canWrite) AND ((microtime(TRUE) - $startTime <5)));

        // Save data if the file was locked
        if ($canWrite) {
            fwrite($fp, $dataToSave);
            flock($fp, LOCK_UN);
        }

        fclose($fp);
    }
}</code>

Example usage:

<code class="php">$ini_array['lu_link'] = '#FFFFFF';
write_php_ini($ini_array, "sample.ini");</code>

These functions provide a straightforward way to access and modify values in your PHP INI files.

The above is the detailed content of How to Read and Edit 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