PHP Includes

This YouTube video was created by Steve Griffith.

PHP has the ability to include multiple files into a single PHP file. This is very powerful tool is how templates can be created using PHP.

There are four ways to include files into PHP. While they all work in same basic way, there are slight differences between all four.

include

The includeopen in new window statement will fetch an external file and include all of its content inside the parent page. If the page cannot be found, PHP will issue a notice as continue rendering the rest of the file.

include "includes/database.php";
include "includes/header.php";
include "includes/navigation.php";

include_once

The include_onceopen in new window statement will fetch an external file and include all of its content inside the parent page, ONLY if it has not already been included. If the page cannot be found, PHP will issue a notice as continue rendering the rest of the file.

include_once "includes/navigation.php"; 
include_once "includes/navigation.php"; 
include_once "includes/navigation.php";

The example above would fetch and include the first navigation.php file, however the second and third copies would not be included. The PHP interpreter would check each time to see if the file was already included. If not, then it will fetch and include the file, otherwise the line of code will be ignored.

require

The requireopen in new window statement will external file and include all of its content inside the parent page. If the page cannot be found, PHP will issue an ERROR and stop rendering the file.

require "includes/database.php";
require "includes/header.php";
require "includes/navigation.php";

require_once

The require_onceopen in new window statement will external file and include all of its content inside the parent page, ONLY if it has not already been included. If the page cannot be found, PHP will issue an ERROR and stop rendering the file.

require_once "includes/navigation.php"; 
require_once "includes/navigation.php"; 
require_once "includes/navigation.php";

The example above would fetch and include the first navigation.php file, however the second and third copies would not be included. The PHP interpreter would check each time to see if the file was already included. If not, then it will fetch and include the file, otherwise the line of code will be ignored.

Using the require or require_once command tells the PHP interpreter that your page should NOT run without the contents of the other page. An example of this would be a security test to see if a user is logged in or a connection to a database. Without those two things there is no point in trying to load the page. The user will either be viewing content that they potentially are not allowed to see or there is no content to load because the database is unreachable.