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.
[define] 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 if(isset($ini['define'])) { 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 ;.
Update
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 </files>
No comments:
Post a Comment
If you found this page useful, or you have any feedback, please leave a comment.