What is the difference between require() and include() in PHP?

2 minute read

The key difference between require() and include() is that if you require() a file that can’t be loaded (e.g. 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:

<?php
$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.

From php.net:

Note: Prior to PHP 4.0.2, the following applies: require() will always attempt to read the target file, even if the line it’s on never executes. The conditional statement won’t affect require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.

Tags:

Categories:

Updated: