How To Use Custom ini Files With PHP

Wednesday, June 3rd, 2009

The special 'config' file is a very important file at the heart of almost every web/software application. The config file typically holds information that will be used over and over again, such as database info. There are plenty of ways you can go about creating a config file. Many just create a new file with some defined constants and include the file. Others use a database or XML file for config storage. Today, we will have a look at a simple example of using a custom ini file to set our preferences.

The config.ini file

Setting up a config.ini file is super simple. Create a new file on your server named 'config.ini' and type in something like below:

;This is a basic ini file setup
;
;Note how comments are made with semi colons?

[version_info]
version_number = 3.0
version_stable = true
last_updated = 06/23/08

[db_info]
db_name = MyDatabase
db_user = root
db_pass = root

The PHP file

Now all we need to do is parse the contents of the file, we can do this using the parse_ini_file() function.

<?php
ini_set("display_errors", "1");
error_reporting(E_ALL); 

//Parse and store the ini file, this will return an associative array
$config_info = parse_ini_file('config.ini', true);

//Debug
print_r($config_info);

//Example usage
echo 'You are currently running version ' . $config_info['version_info']['version_number'];
?>

This would output You are currently running version 3.0

Other options

As I said, this is just one way to store important configuration data. A few other options include, but are not limited to:

  • XML File
  • PHP File
  • Database Storage (obviously where applicable)

Simple right? Obviously, this is a super simplified example, but you can see how easy and helpful a basic .ini file can be! What are some of your methods for storing config preferences?


If you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!

ABOUT THIS AUTHOR

Hi, I'm Drew Douglass and I make sure Dev-Tips.com runs smoothly. I also work for Envato Support and write for NETTUTS.com and ThemeForest.net. I'm passionate about anything web development related, especially php, WordPress, MySQL, and jQuery. Feel free to follow me on twitter.
  1. Ethan
    June 3, 2009 at 7:29 pm
  2. June 7, 2009 at 3:58 am
    • June 7, 2009 at 12:12 pm
  3. November 3, 2009 at 1:43 pm
    • November 3, 2009 at 3:09 pm

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Popular Series

Output Buffering Articles
Build a Custom AJAX and PHP Contact Form
The Ultimate Image Gallery Manager.
ThemeForest Premium Site and WordPress Templates