This tutorial explains How to parse, read INI files, and write Ini file

PHP Read INI File file

Let’s create a config.ini file for this example

; Application Configuration Settings

[database]
; Database server address
server = localhost

; Database port number
port = 3306

[User]
; Admin username
username = admin

; Admin password (avoid including actual passwords in comments!)
password = secret

 ; Application Settings

[application]
host = "localhost"
port = 8080

[feature]
is_ssl = true
feature_enabled =  true

Ini file contains the below sections

  • user
  • database
  • application
  • feature

Each section contains key and value pairs.

  • Read without Sections

parse_ini_file is used to read the content of the config.ini file and write it into an array object in PHP.

Syntax:

parse_ini_file(file, sections, mode)

Return an Array on successful read, else false returned.

Parameter values: file: Required ini file path sections: Optional Boolean value, true, indicates sections to read into a multi-dimensional array with each row containing an Array of section names and values. Default is FALSE mode: scanner mode - INI_SCANNER_NORMAL: Default - INI_SCANNER_RAW: Read without typing - INI_SCANNER_TYPED: Read with type and do the conversion to different types - numbers converted to Integer type - true, on, yes converted to TRUE - false, off, no converted to FALSE - null converted to NULL

Read the ini file into an array

The below example reads ini file into an array without sections

$config = parse_ini_file("config.ini");
print_r($config);


// Find  if the ini file  is read successfully
if ($config !== false) {
    // Access individual settings
    echo "hostname: ". $config['hostname'] . "\n";
    echo "port: " . $config['port'] . "\n";
    echo "username: " . $config['username'] . "\n";
} else {
    echo "Read INI file Failed.";

You can a

Array
(
    [server] => localhost
    [port] => 8080
    [username] => admin
    [password] => secretpassword
    [host] => localhost
    [hostname] => localhost:3201
    [user] => admin
)

Read the ini file with sections

This example reads an ini file with sections and stores it in a multi-dimensional associative array of sections and key-value pairs. Sections are nested with key and value pairs as nested arrays.

$configWithSections = parse_ini_file("config.ini",true);
print_r($configWithSections);

parse_ini_file reads the files and converts them to an array. true: parameters tell to read sections.

Array
(
    [database] => Array
        (
            [server] => localhost
            [port] => 3306
        )

    [User] => Array
        (
            [username] => admin
            [password] => secret
        )

    [application] => Array
        (
            [host] => localhost
            [port] => 8080
        )

    [feature] => Array
        (
            [is_ssl] => 1
            [feature_enabled] => 1
        )

Below is How to read keys and values using

<?php
$configWithSections = parse_ini_file("config.ini",true);
print_r($configWithSections);
// Find  if the ini file  is read successfully
  if ($config !== false) {
      // Access individual values
      echo "server: " . $configWithSections['database']['server'] . "\n";
      echo "port: " . $configWithSections['database']['port'] . "\n";
      echo "username: " . $configWithSections['User']['username'] . "\n";
  } else {
      echo "read INI file Failed.";

}

Output:

server: localhost
port: 3306
username: admin

How to Write an Array into an ini file in PHP

  • First, Create key and value pairs in an array per section
  • Create a write_to_ini function, does the following things
    • Takes an array of pairs, section names, and file names to write
    • Iterate pairs and append to a variable
    • Append variable content to a file using the file_put_contents function, Operation Mode is FILE_APPENDIt, It does creates a file if not exist, and writes variable content into a file, else it appends the variable to a file.
    • Returns the TRUE for successful write, else FALSE
  • It creates a file successful, check the result.ini file for content

Here is an example

<?php
// Create an array of pairs
$databaseSections = [
    'server' => 'localhost',
    'port' => 3000,
];

// Write configuration to the 'database' section
$success = write_to_ini($databaseSections, 'database', 'result.ini');

// Check if the write-to file successful
if ($success) {
    echo "Write to file successfully!";
} else {
    echo "Write INI file Failed.";
}
// Function to write settings to a specific section in an INI file
function write_to_ini($config, $section, $file) {
    $content = "; [$section] Configuration\n";

    foreach ($config as $key => $value) {
        $content .= "$key = $value\n";
    }

    // Append content to file
    return file_put_contents($file, $content, FILE_APPEND) !== false;
}

On Running the above code, It generates the result.ini file

; [database] Configuration
server = localhost
port = 3000

Important point: Sections, Key and value pairs are case sensitive. For example, Database and database are both different section names