Difference Between include() and require() in PHP

This article is created to differentiate include() and require() function of PHP.

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

PHP include() Vs require() Example

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

  • The include() produces a warning message (E_WARNING) upon failure, and the script continue its execution
  • The require() produces a fatal error (E_COMPILE_ERROR) upon failure, to halt the execution

Here is an example uses 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()

And here is an example uses the require() function:

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

The output is:

Before require()

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

PHP Online Test


« Previous Tutorial Next Tutorial »