Thursday, November 13, 2008

The Difference Between require() and include()

The key difference between require() and include() is that if you require() a file that can't be loaded (eg if it isn't there) then it generates a fatal error which will halt the execution of the page completely, and no more output will be generated. On the other hand, if you include() a file that can't be loaded, then this will merely generate a warning and continue building the page.

What one you should use depends on the situation; require() is best suited for loading files that are essential to the rest of the page - for example if you have a database driven website then using require() to include a file containing the database login and password is clearly preferred over using include(). If you used include() in this situation, then you may end up generating more warnings and errors than you had intended.

include() should be used when it isn't essential for that file to be loaded to execute the page. This is best used in situations where the file isn't essential to the processing of the page (for example a footer file), so if the file isn't present then the user can still view the site. You should, of course, make sure that all files you include() and require() are going to be available.

In PHP versions prior to 4.0.2. there was slightly different behaviour of require(). If you used a require() statement in an if block then the require() statement will always make sure that the file you're require()ing is readable, regardless of whether the condition was true for that if block to be processed. This is best illustrated with the following code example:

$a = 1;
if($a == 2) {
require("header.php");
}
?>

In this example, PHP versions before 4.0.2. will always make sure that header.php is available, but it will only actually execute the contents of it if $a is equal to 2.


More Explanation:

The principle differences between include() & require() are :
(1).When “Include()”ed file is not found,only warnings will be displayed& the script will continue to execute further.
But,when “require()”ed file is not found,fatal errors will be displayed & the script will halt execution.
When we are dealing with non-confedintial data,
inlude()is preffered.
e.g. When we are dealing with a form which posts Sachin Tendulkar’s age & no. of centuries ,after posting the form,
the variables age & no.centuries will be displayed on the URL of the opened active file.
If “include()” ed file doesn’t exist ,only waning will be given & the script will follow its execution afterwatds.

with including “require()” in our file ,we can safely process over confidential data ,such as user login form. Here both login ID & passwords are checked & script will continue only when “require()” function gets required file,otherwise,it will halt the script showing fatal error.


No comments: