Including files bring more convenience in managing your code. As the name states, include is a function that will simply dump the contents of the included file into the current file. This is cool because some times you may need some code that should be available on all pages. Say a menu or a website header.
Including files saves a lot of efforts by writing your code multiple times on each page. Yeah I know you copy and paste but that requires some more efforts too comparatively. Suppose you suddenly add a page in menu. Then? You need to update all the files. Using include function we can just create one file and include it all over in other files. Hence editing only one file will modify code in your other files.
I hope I am clear enough in explaining this to you. Let us start with an example. Oh before that, the syntax for include function is
<?php include("filename.php"); ?>
So let us first create a file called menu.php The file content would be something like this.
<a href="#">Home</a> - <a href="#">About Us</a> - <a href="#">Contact Us</a> <br />
Now let us create an index.php file. The index.php file will contain some content as well as the menu file. So this is what the code will be in index.php file
<html> <head> <title>Testing Include File</title> <head/> <body> <?php include("menu.php"); ?> <p>This page is created to display the working of include function</p> </body> </html>
See the preview
The require function is almost same as the include function. The only difference is in error handling. When the included file doesn’t exist, a warning is displayed and the execution is preceded.
Where as when a file included via require function does not exist, then a fatal error is displayed and the execution is halted at the same line. The syntax is
<?php require(“filename.php”); ?>