Difference Between include() and require() in PHP

This article is created to differentiate between the include() and require() functions of PHP.

The include() and require() functions are used when we need to execute some script from an external file. The only difference is that include() lets the script continue its execution, whereas require() does not, if something goes wrong while executing the script of an external file.

PHP include() vs. require() example

Both include() and require() functions are the same, except that:

Here is an example using the include() function:

<?php
   error_reporting(0);
   
   echo "Before include()<BR>";
   include("unknown.php");
   echo "After include()<BR>";
?>

The output is:

Before include()
After include()

The error_reporting(0) function call in this PHP code disables error reporting. The phrase "Before include()" is then printed to the webpage. include() is used to include the contents of another file into the current file.

In this example, "unknown.php" is being included, which is likely not present in the same directory as the current file. If the file already exists, its contents are appended to the current file.

A warning message will be generated because the file "unknown.php" does not exist. However, the user will not see this warning because error reporting has been disabled. Instead, the code will bypass the include() function call and output "After include()<BR>" to the webpage.

Here is an example using the require() function:

<?php
   error_reporting(0);
   
   echo "Before require()<BR>";
   require("unknown.php");
   echo "After require()<BR>";
?>

The output is:

Before require()

This PHP code is similar to the previous example, but utilizes the require() function rather than include(). The function require() is used to include a file within the current file. Unlike include(), however, if the required file does not exist, a fatal error will occur and script execution will stop.

Note: The error_reporting(0) statement is used to turn off error reporting.

PHP Online Test


« Previous Tutorial Next Tutorial »