learn

Include and Require

category: Advanced
Created by: Dr.Ferrous

Include and Require

category: Advanced
Created by: Dr.Ferrous
twitter google+ facebook pinned 

Once you have created a script or an HTML content that you want to use in multiple pages is best stored in an external file and included in each page you want to use it. This is accomplished with the include and require functions.

PHP has four commands that can be used to include code from an external file:

  • include() - generates a warning if the external file is missing, but the script will continue execution
  • include_once() - prevent the same file from being included more than once in a page. If the external file is missing, generates a warning and attempts to continue processing the script.
  • require() - If the external file is missing, generates a fatal error, and the script will stop.
  • require_once() - prevent the same file from being inserted more than once in a page. If the external file is missing, stops processing the script and throws a fatal error.

To include an external file, you pass the file path to one of these four include functions as a string (single or double quotes).
Syntax:

or

The following example scripts will not work in this lesson because the external files do not exist.

The file path can be either absolute or relative to the current document.
An absolute path says where a file is starting from the root directory of the computer:

 

A relative path uses the position of the current script file as the starting point. To move back one folder, use two periods together followed by a slash (../).

 

For example, if you have a standard header and menu files (in a "templ" directory located in the curent folder), called "header.php" and "menu.php", that should be used on all pages. To include these files in a PHP script, use the include() (or require() ) function:

 

With this method you can insert the same header and menu code in any PHP files in the Web site, all pages in the Web site can include the code of the header and menu files, and if you need to update the header or the menu later, you will only need to make changes in the "header.php" or "menu.php" file.

Using parentheses with the include commands is optional, the following would also work:
                include 'includes/file.php';
                include '/usr/MAMP/htdocs/includes/file.php';

When using a relative file path, you can use use "./" to indicate that the path begins in the current folder. Example:
                include('./includes/file.php');