PHP Include

The PHP include function is pretty self-explanatory. This function simply includes the contents of another file wherever you insert the code.

You may also wish to read the lesson on the PHP require function.

The PHP include and require function are almost identical, except for the fact that the include function will continue to execute if it runs in to an error, while the require function will stop immediately if it runs in to an error.

What this means is that if you have an error when using the include function, you will get a warning, but the script will continue to execute (which will most likely cause troubles in the functionality). If, however, you are using the require function, you will get a fatal error and no further action is taken.

When designing PHP based websites or code, you will most likely use the include function time and time again.

For example, if you take note of the sidebar layout on the right side of your screen, then browse to my homepage, you will notice that the sidebar changes. This is because I have designed two different sidebars saved as two different files. Instead of inserting all the mess of code it takes to generate my sidebar in every single page of my site, I simply create a sidebar, then include that one file in each page. I can easily choose which file to insert on each page of my site as it only takes one line of code, but will alter the entire sidebar layout.

PHP Include Usage

To include a file using the PHP include function, you simply use the following format:



Now, let’s understand how it works by looking at an example.

PHP Include Example

Let’s create one file and name it “header.php”. In it, we will insert the following code:



John's Website
Welcome to my website!
Feel free to take a look around.

If you view that file by itself in your browser, it will look like this:

John’s Website
Welcome to my website!
Feel free to take a look around.

Let’s create another file called “index.php”. In it, we will insert the following code:


However, there's not much here because I'm not done designing my website just yet.

Now, if you open index.php in your browser, it will look like this:

John’s Website
Welcome to my website!
Feel free to take a look around.

However, there’s not much here because I’m not done designing my website just yet.

Notice that by using the include function, we were able to include the entire contents of header.php into the top of our index.php file.

You may also wish to read the lesson on the PHP require function.