This is a way to allow you include the content one PHP file into another PHP file. To achieve this you will you either of the two functions:
The benefit of this is that certain elements can be reused in multiple pages of a website. For example, you may want to have a navigation bar and a footer that appears in all your pages. Instead of creating them in all the pages, you can just create on file containing the header and another file containing the footer. Then you can include this file in the pages. Any changes you make to these included file would reflect in all the pages. In this way, it would be easier to change the layout of a quicker.
Let’s take a closer look at these two functions
1. The include() Function
The include() function takes all the text in a given file and copies them into the other file. If there are some error loading this include file, then the interpreter would output a warning but the script would continue executing.
For example, the code below contains a possible navigation bar for my website www.kindsonthegenius.com. I create as save this menu in a file call navbar.php.
<a href="https://www.kindsonthegenius.com/home">Home</a> - <a href="https://www.kindsonthegenius.com/java">Java</a> - <a href="https://www.kindsonthegenius.com/python">Python</a> - <a href="https://www.kindsonthegenius.com/javascript">JavaScript</a> <br />
Now, in any of the page you would like to use the this, you can now include the navbar.php like this.
<html>
<body>
<?php include("navbar.php"); ?>
<p>This how to include a file</p>
</body>
</html>
2. The require() Function
Similar to the include() function, the require function also copies a specified file into another file. However, the difference is on how they handle errors. When there require() function encounters a problem loading the file, the a fatal error is generated and the execution of the script is halted.
For example let’s use the include() function and require() function to include an file that does not exist.
<html>
<body>
<?php require("nofile.php"); ?>
<p>This how to include a file</p>
</body>
</html>
When this code executes, the require function encounters an error since the file does not exist. Program terminates. However, if you use the include() function, it would continued and output the text in the next line.