Parse ini file

What is INI file

An INI file is a configuration file for computer software that consists of a text-based content with a structure and syntax comprising key–value pairs for properties, and sections that organize the properties.

parse_ini_file function

Parse ini file is a function to parse any configuration file which has key-value pair
This is required when you want to keep all application-level configuration parameters in one place
Maintaining configuration level parameter/variables is easy when you use ini file
You need to make changes in one file and it will reflect changes throughout the application


Syntax

parse_ini_file(file, process_sections, scanner_mode)

myapp.ini

#comment goes here

APP_NAME	= UMS
ADMIN_EMAIL	= admin@umsapp.com


#local database credentials
[localdb]
DB_HOSTNAME	= localhost
DB_USERNAME	= root
DB_PASSWORD	= ""
DB_PORT		= 3306
DB_NAME		= ecom


#production database credentials
[proddb]
PRD_DB_HOSTNAME	= localhost
PRD_DB_USERNAME	= root
PRD_DB_PASSWORD	= ""
PRD_DB_PORT	= 3306
PRD_DB_NAME	= ecom

global_functions.php

function getConnection() {
	
	$db = parse_ini_file('config/myapp.ini', true)['localdb'];
	
	$conn = null;
	
	$servername	= $db['DB_HOSTNAME'];
	$dbname		= $db['DB_NAME'];
	$username 	= $db['DB_USERNAME'];
	$password	= $db['DB_PASSWORD'];
	
	try {
	  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
	  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);	
	} catch(PDOException $e) {
	  echo "Error: " . $e->getMessage();
	}
	
	return $conn;
}

Ref: https://www.w3schools.com/php/func_filesystem_parse_ini_file.asp

Leave a Reply

Your email address will not be published. Required fields are marked *