Blake O'Hare .com

PHP Tutorial Part 6 - Using Multiple PHP Files

It's hard to tell from these simple examples I've been giving throughout this tutorial series, but after writing a real website for any length of time, you will realize that your code will start to get repetitive between pages. PHP allows you to insert the contents of another PHP file within your code. This method is called include...

<?
    include "common_header.php";

    echo "The body of my page is here!";

    include "common_footer.php";
?>

This plops the contents of common_header.php and common_footer.php into your code at run-time. This basically is a quick and simple way to create a unified look for your entire site without writing the HTML code more than once. You define what appears at the top of the page in one file and what appears at the bottom of the page in another file and you include them at the beginning and end of each of your PHP files. There are some sites I've made where this is the only aspect of PHP I use since it makes life so much simpler especially if you want to make changes to the way each page appears.

If the file you specify is not found, then a simple error message is displayed. However if you want the PHP script to halt entirely if it can't find the file, then there is a similar command called "require".

<?
    require "common_header.php";

    echo "The body of my page is here!";

    require "common_footer.php";
?>


Next: Interacting with a database
Back to Tutorial Overview