How failures in execution are handled with include() and require() functions in PHP ?
The include() and require() functions use the code or text present in the specified file and copy the code/text into the file which uses the include/require functions. The benefit of using these functions is that it saves time and lines of code because it helps us to reuse the functionalities that are already defined where ever we want by a simple single-line statement. The entire functionality of include() and require() methods are the same. But they behave differently when an execution failure happens.
include() function: It allows developers to reuse the existing functionalities with less code. The function produces a warning when any included file is missing and the script will continue to run to provide an output. So whenever we want a script to run and show users the output even when the files specified in the include statement are missing, then the include() function can be used.
Example 1: This sample example is using the include() function in PHP. The below code is the content for the “footer.php” file.
Include this “footer.php” file into another PHP “main.php” file.
main.php: In the below code, the include() function is used to include the “footer.php” file. The functionality of the “footer.php” file can be used in the “main.php” code. Even if the “footer.php” file does not exist, the HTML file will continue to run and provides output.
Example 2: If we try to include the non-existing PHP file into “main.php” using the include() method, we will still get an output with a warning message for the include statement. Let’s look into the code that includes a not existing PHP file.
require(): The require() function performs same as the include() function. But it produces an error when the file specified in require function is missing. The require() function will produce a fatal error when any file specified in require function is missing and stops the script from running. This function is used in complex PHP applications that avoid compromising application security and integrity if any missing files are included.
Example: This sample example is using the require() function in PHP.
header.php: The below code is the content for the “header.php” file.
demo.php: Try to include this “header.php” file into another PHP “demo.php” file, will see the contents of both the files.
demo.php: If we try to include the file which does not exist using the require() function, then a fatal error is produced and the script stops running.
Note: Unlike include() function, require() function will not proceed script to run, if file specified in the require() function does not exist. It throws a fatal error message.