Google analytics code

Sunday, October 11, 2009

PHP: Creating your own custom ini config file

In a continuing effort to make my life more difficult I've decided to write my own MVC. I could have easily used one of many frameworks(Zend Framework, Cake, Symfony, etc ...) but I was really interested in what it takes to write one. So far it's been a great experience and I've learned a lot about PHP5.

One of the things I noticed about a lot of the MVCs is they store settings in an external ini file. I had no idea how they pulled the information out of them until I ran across this article on IBM's website. They mentioned a function called parse_ini_file. This function has been around since PHP4, but I never knew about it. You could fill the grand canyon with the things I don't know, but let's focus on this for now.

This function allows you to read a external ini file and it returns an array of properties. You can also configure it to return an associative array of values grouped by category.

This allowed me to move a lot of settings into an external file and clean up a huge chunk of code. The problem is many of the variables I defined were dynamic. parse_ini_file doesn't evaluate external PHP code. The trick to that is to run eval on things you want it to parse.

Here is an example of some code I have stored in an external file.
PATH_HTTP = "http://{$_SERVER['HTTP_HOST']}/test_site/"

I created a function that will parse the ini file and will run eval on anything in the define group.
//configure define. this will parse php code
  foreach($ini['define'] as $key=>$item)
    define($key, eval("return \"{$item}\";"));

The important part to note when using eval is that it doesn't return a value. If you want to capture the evaluated variable prefix the variable with "return" and make sure to end the line with a ;.

An important thing to note is that ini files can be read very easily in a web browser. You'll want to set up a .htaccess file that blocks viewing of ini files. You can copy-paste this into a .htaccess file at the root of your site.
<files *.ini>
order allow,deny
deny from all

No comments:

Post a Comment

If you found this page useful, or you have any feedback, please leave a comment.