Using PHP Include

What is PHP Include?

In website development, the include() method is a standard php function that allows a developer to insert files into a webpage.

For example a developer may wish to use an include() as a way to display a navigation bar or a footer across multiple webpages without having to copy and paste the code into each new page. Another distinct advantage here is that you do not have to update each page in your site when making a change. Something that would be incredibly painful and error-prone to attempt by hand on any site with more than just a few pages.

Example

PHP is well known for being an excellent platform to quickly develop webpages and include() is one of the best examples of why this is the case.

For this example you need the following:

  1. A text editor (notepad++ is a great option since it’s free)
  2. A working web server with php (almost all web hosting packages come with php). I will be posting a how-to for setting up a Linux web server in the next couple weeks.

Step 1 – Create the directories

For this example all we need is a project root directory and one sub-directory called “includes”.

dirStructure

 

Name your project folder whatever you want. The includes folder can be named anyway you choose as well, but pay close attention to the examples so that you can adjust your code as necessary.

Step 2 – The header

Within the “Includes” directory create a file called “header.php”. This file will contain all the code for the head section of our webpage as well as the navigation menu.

Copy the following code into your text editor:

<?php
/**
 *
 * The head of each document. This should be included in all pages
 */

function setTitle ($title)
{
    echo "<title>$title</title> \n";
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php setTitle($title); ?>
    <meta name="description" content="<?php echo $description;?>">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
</head>

Explanation

Make note of lines 7 – 10, 18, and 19.

The setTitle function and the $description variable will come in handy when you begin to create other your other webpages. These represent two ways in which you can dynamically set the title and description elements.

function setTitle ($title)
{
    echo "<title>$title</title> \n";
}

This is a fairly simple php function that we have named “setTitle” it takes in a variable called “$title” and then inserts that variable into a title tag that is generated by the “echo” function.

We will define $title when we create the index page. It’s value will be defined each time a new page is written.

Line 18:

<?php setTitle($title); ?>

Calls the function and inserts the title into the <head> element. Remember that PHP is not sent to the web browser. It gets executed at the server, in this case it outputs HTML and sends that to the browser.

Line 19:

<meta name="description" content="<?php echo $description;?>">

This is the second way in which we can add text to the page. This will insert the $description variable into the <meta> description tag. This again is useful for dynamically generating a description on each page. $description will be defined in step 3.

HTML Tags

Notice that the <html> tag does not get closed in this example. In the next example we will open the <body> tag and not close it until we create the footer. The webpages we are making are not made of one simple HTML file, these pages will be combined using includes to generate a page at the server which will then be sent to the browser.

The navigation

Still in the “header.php” file we now need to add the navigation bar.

<body>
<nav class="navbar navbar-inverse navbar-static-top">
            <a href="http://www.blackswampweb.com">Black Swamp Web</a>
        </div>
        <div id="navbar">
            <ul class="nav navbar-nav">
                <li><a href="index.php">Home</a></li>
                <li><a href="#">Some Page</a></li>
                <li><a href="#">Another Page</a></li>
            </ul>
        </div>

    </div>
</nav>

This is a fairly straight forward navigation structure. Since we added the bootstrap cdn in the head this should create a nice horizontal layout. If you are not familiar with this HTML you might want to start with a few examples at codecademy.

Step 3 – The index page

Within the “Project” root directory create a new file called “index.php” this file will represent the home page for our project site.

Copy the following code into your text editor (at the top):

<?php
/*
*Home page
*
*/
$title = "The best home page ever!";
$description = "Most awesome description we could think of!";
include('Includes/header.php');
?>

Remember step 2 when I mentioned that the $title and $description variables would be defined later. Well it’s later. Notice that both of these are just strings and PHP doesn’t make us define them as such. All variables in PHP must start with a “$”.

This first snippet also shows the include() method that we’ve been waiting to use. This method takes in a file path, in this case the path is “Includes/header.php” but it could be something else if you made up your own names. It then evaluates that file and includes it’s output into the file that calls it (in this case index.php).

At this point if you run index.php on your web server you will see the navigation bar we made in the header.php file. You will also see the title we defined in the window header or tab.

Finishing the home page

Insert this code directly under the php closing tag in the index.php file.

<div class="jumbotron">
<h1>Yay! Home Page!</h1>
        <p>Look at the super awesome Jumbotron!!!</p>
        </div>
<h2>H2 tag for whatever comes next</h2>
<p>Less awesome than the jumbtron... but still cool</p>

Step 4 – The footer

The rest of this should be pretty familiar. In the “Includes” directory create a file called “footer.php”. Here is were we will close the open <html> and <body> tags as well as add a copyright, and a couple links.

Insert the following code into “footer.php”.

<?php
/**
 * 
 * The footer. Include on every page
 */
?>
<hr />
<div> 
<footer>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-6">
            <ul>
                <li class="text-primary"><p>Contact Information</p></li>
                <ul>
                    <li class="list-group-item-text">Phone: <a href="tel:5555555555">(555)555-5555</a></li>
                    <li class="list-group-item-text">Email: <a href="#" title="Contact Us">Contact Us</a></li>
                </ul>
            </ul>
        </div>
        <div class="col-md-6">
            <h4 class="text-center">Black Swamp Web </h4>
            <p>Awesome websites!</p>
            <div>
            <p id="copy" class="text-info text-center">&copy; 2015 &lt Black Swamp Web &gt</p>
            </div>
        </div>
</body>
</html>

Notice the last two lines in the above code. This is where the <html> and <body> tags are closed. One last thing.

Open the “index.php” file and append this include() the last <p> tag.

<?php include('Includes/footer.php');?>

This calls the footer we just created and adds it to the index page.

Conclusion

Using include() we can use the power of PHP to build our pages dynamically on the server. Our home page is made up of 3 files a header, index, and footer. Your pages could be made of even more files. Maybe you need a module to insert advertisements. Don’t write it on each page, don’t copy and paste it, don’t repeat yourself. Write it once and include it on the pages you want to, it makes for cleaner code that is modular and can be used in other projects.

The include() method gives us a way to write code that gets repeated throughout a web project once and then append that code onto each new page without having to copy and paste. It also give a safety net when updating a copyright date on a footer, or adding a new link to the navigation menu. Using includes we only need to update one file to make a change on a site rather than updating 10 files, misspelling a link on two of them and completely forgetting about the 11th.

For more on includes see http://php.net/manual/en/function.include.php

Leave a Reply