Sometimes you need to keep the same data across all pages. For example, take case of website that has common navigation menu, footer and sidebar across all pages. When you build a dynamic site it is important that these parts of a website remains common so that users can access website without any confusion. In situations like this include function is very useful in any dynamic php based website.
Include function takes the specified file name and simply inserts the file contents into the script that calls it. As you get into situations where you want reuse the content over multiple pages, this function is going to very handy for you.
Using Include Function
Let’s take an example of sidebar where you’re showing recent posts of your site. You want it to be seen on every page. In a case you can use include function that points to the sidebar.php and so that every file that has this function will include the contents of this file.
Code Sidebar.php
<?php echo "this is sidebar"; ?>
If you want to include this sidebar.php in index or home.php in order to show the text, you need to use include function.
Code Home.php
<?php include("sidebar.php); ?> </body> </html>
It’ll show the text in sidebar.php file on this web page. It’s very easy. But what if you don’t have that file in existence or if you mistype the file name ? In such a case php will throw error on web page and then will continue to show the remaining part of the text.
If you want to check if the file if loaded before executing the page for user, you need to use another function called require. This function will do the same job like include function and will also check if the particular file which is requested exists in folder.
<?php require("sidebar.php); ?> </body> </html>
If the file is not present in the folder, PHP will throw an error on web page and will not execute the rest of the code. This is helpful if you’re working with sensitive data or plugins or media files. It is good practice to use require function instead of include function as it ensures your website is working properly and helps you catch the errors easily.