HowTo – Adding A Site Wide Config File For Your PHP Pages

Filed under: Web Design

phpWhen you are developing a PHP based website there are many times when you end up repeating yourself for various simple things.

A config file that is linked to in the header area of your php files can help you use shortcuts and also reduce the time it takes to make changes if you move your site or if you want to reuse your code for other projects.

This is a little different then setting up a functions file which will hold code snippets the basic idea is to set your vars and then refer to them in shorthand.

For instance in your config.php file you might put

$basepath = ‘/user/public_html/folder/’;
$siteurl = ‘http://www.yoursite.com’ ;
$imgdir = ‘http://www.yoursite.com/images’ ;
$sitename = “jimmy’s sausage site”;
$contactemail = ‘jimmy@sausageworld.com’;

then to use them in your files you simply include the config.php file at the top of any php file that you want to use it in like this.

<?php include(“config.php”); ?>

and use them like this

<img src=<?php echo “$imgdir”; ?>/sausage.jpg>

Now yes in some cases hard coding the info may be faster then adding in the php echo but if you want to change the location of your image directory all you need to do is make the directory on your server and edit your config.php file and everything will be working in just a couple seconds vs search and replace strings through out your site hoping that you got the string replace right.

Other Note

Some coders like to call this file a config.inc as a include file this is fine too.

The way you use this file is up to you.

you can get very creative and provide yourself site wide control through this one file but it does take some pre-planning and trial and error to get the file optimized for each site or application.

If you would like to reuse code within your scripts it is best to place that in a seperate functions.php file.