The two constructs require() and include() are identical in every way except how they handle failure.
include() produces a Warning while require() results in a Fatal Error.
In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. Be warned that parse error in included file doesn’t cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does.
As of PHP 4.0.2 and later, require() can be described, in PHP psuedo- code as :
if (include($filename) == FAILURE) {
print “Fatal error: Unable to require $filename”;
exit();
}
Essentially this means that if it fails, the script WILL end prematurely.
In PHP 3.0.x, and PHP 4.0 versions prior to PHP 4.0.3, require() had another implementation difference - it was always, under all circumstances, performed exactly once. For instance :
for ($i=0; $i<100; $i++) { require(’t1.php’); }
Would have been converted to :
for ($i=0; $i<100; $i++) { …contents of t1.php… }
And then executed, getting the contents of foo.php iterated a hundred times. Another example is as follows :
if (false) { require(”t1.php”); }
Would *still* read the contents of foo.php, turning it to :
if (false) { …contents of t1.php… }
And only then PHP would figure out that it doesn’t even have to execute this code.
As of PHP 4.0.3, the implementation of require() no longer behaves that way, and processes the file ‘just in time’. That means that in the 1st example, the file will be processed a hundred times, and in the 2nd
example, it won’t be processed at all. That’s the way include() behaves (in all versions of PHP) as well.
Other than that, include() and require() have no difference whatsoever, they both behave the same with URLs, safe mode, and anything you can think of.
So, it still makes perfect sense to use require() when it’ll make no sense for your script to continue if the file is not found, which is the case, more
Posted by Dablu as PHP at 8:00 AM IST