Tuesday, January 26, 2010

11:57 PM
The require() function is identical to include(), except that it handles errors differently.


If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.


Error Example include() Function


<html>
<body>


<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>


Error message:


Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5


Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5


Hello World!


Notice that the echo statement is executed! This is because a Warning does not stop the script execution.


Error Example require() Function


Now, let's run the same example with the require() function.


<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>


Error message:


Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5


Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5


The echo statement is not executed, because the script execution stopped after the fatal error.


It is recommended to use the require() function instead of include(), because scripts should not continue after an error.

0 comments: