Welcome to the PHP parse_ini_file() tutorial! In this lesson, we'll dive deep into understanding the parse_ini_file() function and learn how to read INI files in PHP. π
An INI file (Internationalization INI) is a plain text file format for storing configuration settings for various software applications. PHP supports reading and writing INI files using the parse_ini_file() function.
parse_ini_file() is a built-in PHP function that reads an INI file and returns an associative array. This function is helpful for reading configuration settings stored in an INI file within PHP scripts.
To use parse_ini_file(), first, you'll need an INI file. Let's create one for our tutorial:
[database]
host = localhost
user = root
password = your_password
dbname = your_databaseNow, let's read the above INI file using parse_ini_file():
<?php
$ini_file = 'config.ini'; // Replace with your INI file path
$ini_array = parse_ini_file($ini_file);
// Accessing the array values
$host = $ini_array['database']['host'];
$user = $ini_array['database']['user'];
$password = $ini_array['database']['password'];
$dbname = $ini_array['database']['dbname'];
// Print the values
echo "Host: {$host}\n";
echo "User: {$user}\n";
echo "Password: {$password}\n";
echo "DB Name: {$dbname}\n";
?>π‘ Pro Tip: You can also pass an optional third argument to parse_ini_file() to specify the INI section to read.
Let's take a real-world scenario where we have multiple INI files for different environments, such as development, staging, and production.
// config_development.ini
[database]
host = localhost
user = root_dev
password = your_password_dev
dbname = your_database_dev
// config_staging.ini
[database]
host = staging.example.com
user = root_staging
password = your_password_staging
dbname = your_database_staging
// config_production.ini
[database]
host = production.example.com
user = root_prod
password = your_password_prod
dbname = your_database_prod<?php
function getDatabaseConfig($environment = 'development') {
$ini_file = "config_{$environment}.ini";
$ini_array = parse_ini_file($ini_file);
return $ini_array['database'];
}
$config = getDatabaseConfig();
$host = $config['host'];
$user = $config['user'];
$password = $config['password'];
$dbname = $config['dbname'];
// Print the values
echo "Host: {$host}\n";
echo "User: {$user}\n";
echo "Password: {$password}\n";
echo "DB Name: {$dbname}\n";
?>In this example, we created a function getDatabaseConfig() that accepts an environment parameter and reads the corresponding INI file based on the environment. This allows us to easily switch between different environments without modifying the PHP script.
Which PHP function reads an INI file and returns an associative array?