As we know PHP allows us to write different functions and different elements that can be used multiple times into multiple pages. Scripting the alike function in multiple pages is a task of great effort and will be devoured our time.
It can be avoided if we follow and use the concept of file incorporation of which helps us to include different files including text or codes into single programming which saves the effort of writing the full function or code multiple times. it also provides another dominance.
Contents
Include() VS Require() in PHP
If we want to change any code then rather than editing it in all the files, we just need to edit the source file and all codes will be automatically changed. In this post, I have two functions that will help us to include files. These function are called include() and require(). Here are some difference between include and require
include() function
This function is used to copy all the contents of a file called inside of the function, text intelligent into a file from which it is called. This happens before the server carry out the code.
Example:
example i am taking a file which name is header.php:
<?php // file to be included echo "Hello wholeblogs.com"; ?>
Now let’s go and try to include this file into another PHP file such as the index.php file. We will see that the contents of both the file are shown or not.
<?php include("header.php"); echo "<br>Above File is Included"; ?>
Output:
The require() function
The require() function carry out alike as the include() function. It also takes the file that is required and past the whole code into the file from where the require() function was called. Here is one of the most difference between the include() and require() function which we will see following this example:
Let’s have a file called footer.php with the following code:
<?php // file to be included echo "Hello wholeblogs.com"; ?>
Now if we try to include this file I will need to help require() function this file into a web page like wholeblogs.com we need to use an index.php file. We will see that the contents of both the file are shown.
<?php require("footer.php"); echo "<br>Above File is Required" ?>
include() VS require()
Both function take action as same and produce alike results, but if by any chance a fatal error is born, then the difference comes to the surface. Let’s look at the following code:
<?php include("header.php"); echo "<br>Above File is Included"; ?>
Now if we don’t have a file name header.php, then in this case of the include(), the following output will be shown with warnings about a missing file, but at least the output will be shown from the index.php file:
OUTPUT:
Above File is Included
In this case of the require(), if the file PHP file is missing, a fatal error will arise and no output is shown and the execution halts.
Read more: How to run while loop with a table in PHP