If there is one feature that is highly useful and used by novices and experts alike its SSI (Server Side Includes). It reduces the need to copy paste repetitive code and you get a cleaner code. PHP has two functions for including files include() and require(). There is a lot of confusion on which to use when because both of them basically perform the same function of including the specified file but the difference comes by how they handle files.
Error handling in include()
When using the include() function if the specified file doesn’t exist a warning is displayed and execution of the following lines continue. Take a look at the code below.
<?php include("missing_file.php"); print "<h3>Rest of the content</h3>"; ?>
Here there is no file named missing_file.php, executing the code will display the following error
As seen above a warning is displayed and the rest of the lines are executed. Now lets see how require handles errors
Error handling in require()
As the name implies the file called in the required function is definitely REQUIRED and if it doesn’t exit a fatal error is displayed and the execution stops. Let me use the similar code used above with some modifications
<?php require("missing_file.php"); print "<h3>Rest of the content</h3>"; ?>
Take a look at the error message when this code is executed
After the fatal error the print statement is not executed.
When to use which function ?
So by now you understand the difference between PHP include() and require() functions so which is the right place to use either of these functions? If you’re using SSI (Server Side Includes) for displaying footers, banners or advertisements then it is safe to use include() function because a missing banner or ad file is not a reason to stop the execution of the whole page.
Use the PHP require() function where ever a file is REQUIRED i.e., if a user defined function or class is need by every file for performing some operations the call the file using require() function. A good example is calling PEAR files in your PHP code.
[…] auto_prepend_file and auto_append_file. These two PHP directives perform the same function as require() but they do it globally on all PHP scripts. The PHP auto_prepend_file and auto_append_file […]