PHP File Inclusion- Include the content of a PHP file into another PHP file
PHP File Inclusion | include () and require () Function.
How Can include the content of a PHP file into another PHP file?
PHP File Inclusion, Therefore, we can include the content of a PHP file into another PHP file before the server executes it.
This is possible when we use include() and require() Function then we can include one PHP file into another PHP file.
The include() Function
if you want to create functions, headers, footers, or elements that can be reused on multiple pages use include () and require Function.
I will suggest to you If there is any change required then instead of changing thousand of files you can just change the included file.
This will more helpful to developers make it easy to change the layout of the website with minimal effort.
suppose you want to create a simple menu for your blog or website.
Then can create a file menubar.php with the help following content.
|
1 2 3 4 |
<a href="https://www.tutorialscan.com/index.htm">HOME</a> - <a href="https://www.tutorialscan.com/javascript">JAVASCRIPT</a> - <a href="https://www.tutorialscan.com/sql">SQL</a> - <a href="https://www.tutorialscan.com/php">PHP</a> <br /> |
Here we can create lots of pages as you need and include this file to the header.
Suppose now you are an example.php file there has following content.
|
1 2 3 4 5 6 |
<html> <body> <p>how to include PHP file! you can see the blow</p> <?php include("example.php"); ?> </body> </html> |
Finally, there is the following result −

The require() Function
Let us see The require() function copies, all the text in a specified file into the file that uses the include function.
If comes any problem in loading a file then the require() function then its generates or shows a fatal error and halt the execution of the script.
so, Finally, I will tell so there is no difference in require() and include() except they handle error conditions.
by the way, It is recommended to you use the require() function instead of include() function,
because of scripts should not continue executing if misnamed or files are missing.
If you want to see, You can try using the above example which is given with require() function and it will generate the same result.
you will try following two examples where the file does not exist finally then you will get different results.
|
1 2 3 4 5 6 7 |
<html> <body> <p>its shows how to include wrong PHP file!</p> <?php include("abcmenu.php"); ?> </body> </html> |
the following result will be produced: −
|
1 |
it shows how to include the wrong PHP file! |
Let us see the same example with require() function.
|
1 2 3 4 5 6 7 8 9 |
<html> <body> <p>its shows how to include wrong PHP file!</p> <?php require("xxmenu.php"); ?> </body> </html> |
This time nothing is displayed and file execution halts
You will get the plain fatal error messages or warning messages, nothing at all.
its only depends on your PHP Server configuration.