PHP: Require



Just like 'include', require is used to include a file into the PHP code. However, the difference is that "include" function would give warning in case it fails to open the include the file and would continue the execution of the script.But, require the script would be aborted as seen in the example below:

<?php

include ("file");

echo "this would execute";

?>

Here, if the above code if the file in the include does not exist, the following result would be thrown and echo would still be executed.

Warning: include(file): failed to open stream: No such file or directory in C:\x
ampp\htdocs\test.php on line 2

Call Stack:
0.0224 55352 1. {main}() C:\xampp\htdocs\test.php:0

Warning: include(): Failed opening 'file' for inclusion (include_path='.;C:\xamp
p\php\pear\') in C:\xampp\htdocs\test.php on line 2

Call Stack:
0.0224 55352 1. {main}() C:\xampp\htdocs\test.php:0

this would execute

Note, echo command has execute.

If we use require as follows:

<?php

require("file");

echo "this would not execute";

?>

The following result would be displayed if the file in the required is not found and the script is aborted. Thus, echo would not be executed and it would return no output. Thus, require forces a file to be loaded before the scipt can move on and include tries, but does not enforce loading.

Warning: require(file): failed to open stream: No such file or directory in C:\x
ampp\htdocs\test.php on line 2

Call Stack:
0.0003 55352 1. {main}() C:\xampp\htdocs\test.php:0

Fatal error: require(): Failed opening required 'file' (include_path='.;C:\xampp
\php\pear\') in C:\xampp\htdocs\test.php on line 2

Call Stack:
0.0003 55352 1. {main}() C:\xampp\htdocs\test.php:0