Tuesday, March 31, 2009

PHP require versus include

PHP has 2 commands available for including files within scripts; namely require and include. The 2 are identical except for one important distinction; error handling. If include cannot locate the file to include it emits a warning while require will emit an error. Consider the following code which attempts to include a non-existent file:

<html>
<body>
<p>BEFORE</p>

<?php include("file_no_exist.txt");?>

<p>AFTER</p>
</body>
</html>


The output will be:

BEFORE

AFTER


But if we replace include with require the output would just be:

BEFORE


When the require statement cannot find the file it throws a fatal error which halts execution of the script; nothing after the require statement will be executed. For this reason it is generally considered best practice to use require over include because scripts should not be executing if necessary files are missing or misnamed.

No comments:

Post a Comment