PHP include & require

In this lesson, you will learn about PHP ‘include’ and ‘require’, their usage, and examples to better understand the topic.

PHP include and include_once

The PHP declaration “include” is used to include additional documents in a PHP file. Include and include_once are its two variants. The declaration “include once” contains and evaluates the given file during the script execution. It is similar to the include statement; the only difference is that if a file code has already been included, it won’t be included again. It will only be included once, as the name implies. The PHP interpreter will ignore “Include once” if the file is to be included, and include once returns True.

include statement syntax

<?php
include “file”;
?>

include_once statement syntax

<?php
include_once "file";
?>

Example of Include

Let’s take an example of include; you are creating a website with the same navigation menu across all pages. You can generate a prevalent header and then use the include declaration to include it in each section.

Let’s see how we can accomplish it.

Generate two file names for header.php, index.php.

<a href="/index.php">Home</a>
<a href="/aboutus.php">About us</a>
<a href="/shopping.php">Shopping</a>
<a href="/contactus.php">Contact Us</a>

index.php

<?php
include 'header.php';
?>

The header page having all the links above will be displayed in index.php as output.

Example of Include_once

PHP code from another file can be embedded using the “include once” keyword. A warning is displayed if the file is not found and the script still runs. If the file has already been included, “include once” won’t include that file again.

Note
If you include a file that does not exist using include_once, the return result is false. The return result is true if you include the same file again using include_once.

Example

<?php
var_dump(include_once 'file.ext'); // return bool(false)
var_dump(include_once 'file.ext'); // return bool(true)
?>

According to PHP, the file has already been included once, even though it doesn’t exist. “It is used when optional dependencies that would cause HTTP overhead errors or remote file inclusion that you don’t want to occur twice.”

This concludes the PHP ‘include’ and ‘require’ lesson. In the next lesson, you will learn about PHP require & require_once.