Include, include_once vs. Require and require_once in PHP

PHP

These four functions are used to add a PHP script file in another. This allows you to break your script into several files instead of having a single long file. You could have a file called functions.php with your user defined functions. Then include it in your other files to use those functions.

All four of them behave differently. Let us take a look at how they work.

Include

Includes and evaluates a file. If the file is not present it gives a warning.

Example:
hello.php

<?php
$a = "Hello ";
?>

world.php

<?php
include ('hello.php');
echo $a."World";
?>

world.php

Output:
Hello World

If the file hello.php is not present

Output:
World
Note: The execution of the script continues even when hello.php is not present.

Require

This one also adds a file into the current script for execution. But upon failure to include the file i.e. when the file is not present, require will stop the execution of the script and produce an error.

Example:
hello.php

<?php
$a = "Hello ";
?>

world.php

<?php
require ('hello.php');
echo $a."World";
?>

world.php

Output:
Hello World

If the file hello.php is not present, nothing is printed from the script. An error message will be displayed based on your configuration.

Include vs. Require

Include does not produce an error and continues the execution of the script. It only produces a warning. Require on the other hand, produces an error and halts the script execution.

Include_once and require_once

These two functions will include other PHP files for inclusion. If the file has been required or included before in the script, then it will not be included again. Otherwise the file will be added. Include and include_once are similar and require and require_once work similarly.

Example:
hello.php

<?php
$a = "Hello ";
?>

world.php

<?php
require_once('hello.php');
include_once('hello.php');
echo $a."World";
?>

world.php (If the file is present)

Output:
Hello World