Last Updated: June 11, 2021
·
29.92K
· evertonsilva

PHP :: Database Connection with file .ini

Intro

Use a .ini file to manage your database connection so you can abstract the database type and connection info, in your php apps

The dot ini file

First create a .ini file with the information about your database, like this:

host = localhost
name = dbname
user = db_username
pass = p4ssW0rd
type = mysql

The parameter "Type" is optional, but you can use it to make your application be independent of the database, using for example, the PDO library.

Read the file - parseinifile($file) function

To read the config file into your Class, or connection file with the db, use the php function parseinifile($file) passing the path to config file as parameter

// read the .ini file and create an associative array

$db = parse_ini_file("path/to/config-file.ini");

/* now we can use the info in that file to create the appropriate, string connection, based on type, or just using the other info */

$user = $db['user'];
$pass = $db['pass'];
$name = $db['name'];
$host = $db['host'];
$type = $db['type'];

That's it! Now we got a config file to handle with info about the database. If we needed to change de database type, or user, just change that configuration file and it's done.

4 Responses
Add your response

hmm... why just don't keep database connection data in php config file?
Parsing ini files is additional costs of resources.

over 1 year ago ·

@gwinn - There are a number of reasons to keep database config info in an ini file. Many times developers don't have direct access to the php config file. It also allows for better "encapsulation" of the app - all resources are in one bundle. It would also force you to re-start Apache for changes to take effect.

over 1 year ago ·

Many times developers don't have direct access to the php config file.

True, but we are talking about DB configuration file which placed in your application directory.

It would also force you to re-start Apache for changes to take effect.

For changing a db name, db user or db password? This is not a php configuration, it will change dynamically.

About abstraction from db type: PDO can resolve this problem.

over 1 year ago ·

Most PHP frameworks, if not all, use a config.php file for this. Benefits:

  1. Requiring a PHP file is faster than parsing an .ini file. It's just PHP code.
  2. If the file is under documentRoot, .php file is more secure since its content won't be displayed verbatim by a web server, while .ini file can be served by your Apache or Nginx, if you forget to deny access to it explicitely, resulting in a huge security issue.
over 1 year ago ·