Web Tutorialz - PHP Includes Tutorial

Web Tutorialz

"The home of Tutorialz
on the net"

PHP Tutorials


PHP Includes

Written by Blake Simpson on September 5th, 2010


This article is going to be about probably one of the most handiest functions PHP has to offer. Includes. Read on to find out why!

If you ever have the problem where you've just finished a site for a client. It's fully valid XHTML and CSS. It's probably the best website you've ever made. Then your client comes along and says "Do you think you could add a forum link on that nav bar?"
Putting you through the horrible task of updating one link on all 26 pages. Then includes are definitely in order!

A include is a separate file of any file type that PHP reads then writes straight into where it's been included. This means you just cut your #nav <div> into an include called "nav.inc.php" and your ready to go.

Why .inc.php you ask? The answer to that is simple, for one .inc helps tell you that it's an include file. Then .php on the end stops the file being displayed as plain text. e.g. if a hacker went to http://yourdomain.com/includes/password.inc he would see the PHP password variable in plain text. But if you add .php on the end your server will encode it keeping all your data safe!

But now onto some code.

<?php

include('includes/nav.inc.php');

?>

Now the nav bar will appear and you will only ever have to edit it once! But this isn't the end of it. We need to protect against errors.

If the file isn't found by PHP then a ugly error message will be shown, so do the following to prevent this. It uses an if statement to only include the file if it is found and is readable.

<?php

$nav = 'includes/nav.inc.php';
if(is_readable($nav) && file_exists($nav)) {
include($nav);
}

?>

Now that you are protected from unprofessional looking error messages, you are good to go with an include file that only ever needs to changed once to make a change throughout an entire site!

Thank you for reading. You are reader number 548.

^Back to Top^