Parsing and Modifying INI Files in PHP
Reading configuration from an INI file is a common requirement when building applications that need to persist settings across server restarts or allow non-technical users to tweak behavior without touching source code. While the standard PHP php.ini resides outside your web root, you can easily create custom configuration files inside your project directory using the same syntax.
To read values like lu_link or footerbg from a file such as config.colors.ini, you need to parse the file into an associative array. The core function for this is parse_ini_file(). It accepts the path to the file and several optional flags that dictate how missing keys or duplicate entries are handled.
Here is a basic example of reading a value:
$configPath = __DIR__ . '/config.colors.ini';
// Parse the file into an array
$colors = parse_ini_file($configPath, true); // Use true to treat sections as keys
// Access the specific value
$linkColor = $colors['default_colors']['lu_link'];
$footerBg = $colors['default_colors']['footerbg'];
The first argument is the file path. The second argument determines the return format. If set to false (or omitted), parse_ini_file() returns a flat array where keys are fully qualified, such as default_colors.lu_link. If you pass true, it returns an associative array of arrays, where the outer key represents the section header and the inner key is the variable name.
A frequent mistake occurs when handling sections that lack headers or when duplicate keys exist within a section. By default, parse_ini_file() ignores comments starting with ; or #, but it does not ignore lines that look like section headers if they are empty. To avoid parsing errors, ensure your INI file has at least one blank line between sections. This helps the parser distinguish between a section header and an empty value.
Writing new values requires a slightly different approach because PHP does not provide a native function to overwrite specific keys in an existing INI file without regenerating the entire structure. You must read the file, modify the array, and then write it back. The write_ini_file() helper exists in some environments, but the most reliable method using only core PHP is to use parse_ini_file() to read, manipulate the data, and then use file_put_contents() with a formatted string generated by ini_parse().
However, since ini_parse() is not part of the standard PHP core in all versions, the safest pattern for writing back is to reconstruct the INI format manually or use a dedicated library. If you choose to write it yourself, you can iterate over the array and build a string:
function writeIniFile(string $filename, array $data): void {
$lines = [];
foreach ($data as $section => $values) {
if (is_array($values)) {
foreach ($values as $key => $value) {
// Ensure keys are trimmed and values are properly quoted
$lines[] = "[$section]";
$lines[] = "$key = $value";
}
} else {
// Handle root level keys if any
foreach ($values as $key => $value) {
$lines[] = "$key = $value";
}
}
}
file_put_contents($filename, implode("\n", $lines));
}
In this example, we assume the input $data is structured with sections as top-level keys. A more robust implementation would preserve comment lines and empty lines to maintain formatting fidelity. If you need to preserve existing comments or line breaks while only changing specific values, simply overwriting the file risks losing that context. In such cases, consider using a library like php-pear's Config class or a simple parser that separates comments from data before writing.
When deploying these configuration files in production, remember that INI files are parsed as strings unless you explicitly cast them to integers or floats. For color codes like #F8F8F8, storing them as strings is appropriate. However, if your application expects hex values converted to integers for calculations, ensure you perform the conversion at runtime rather than relying on automatic type juggling.
For larger projects built with frameworks like Laravel, consider using Laravel's configuration system which wraps INI-like functionality with better validation and environment-aware loading.