PHP Include File

You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function.

The two functions are identical in every way, except how they handle errors.

The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).

These two functions are usually used to create functions, headers, footers, sidebar, or elements that can be reused on multiple pages.

This can save the developer a considerable amount of time. This means that you can create a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file for add menu link for that new page.

The include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the include function.

Example 1

Assume that you have a standard header file, called “header.php“. To include the header file in a page, use the include() function, like this example, file home.php :

<html>
<body>

<?php include(“header.php“); ?>

<h1>Welcome to my home page</h1>

<p>Another text</p>

</body>
</html>

and at file header.php :

<a href=”http://www.forcescript.com”>Home</a> |
<a href=”http://proxy-name.com”>Proxy Name</a> |
<a href=”http://www.gbpforex.com”>GbpForex</a>

Example 2

Now, let’s assume we have a standard menu file that should be used on all pages (include files usually have a “.php” extension). Look at the “header.php” file below:

<html>
<body>

<a href=”http://www.forcescript.com”>Home</a> |
<a href=”http://proxy-name.com”>Proxy Name</a> |
<a href=”http://www.gbpforex.com”>GbpForex</a>

and at home.php file :

<?php include(“header.php“); ?>

<h1>Welcome to my home page</h1>

<p>Another text</p>

</body>
</html>

If you look at the source code of the “home.php” in a browser, it will look something like this:

<html>
<body>

<a href=”http://www.forcescript.com”>Home</a> |
<a href=”http://proxy-name.com”>Proxy Name</a> |
<a href=”http://www.gbpforex.com”>GbpForex</a>

<h1>Welcome to my home page</h1>

<p>Another text</p>

</body>
</html>

The require() Function

The require() function is identical to include(), except that it handles errors differently.

(more…)