Difference between include() and require() functions?
This both functions help to include the content of other PHP files into another PHP file. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.
include() Function
While using the include() function it adds the content of the page or file into the file where this function is used.If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.
Syntax :
include 'filename';
or
include('filename');
Let us take an Example of include() function, here I’m creating a header.php file which contains the menu.
<a href="https://www.techlifediary.com">Home</a>
<a href="https://www.techlifediary.com/p/about_20.html">About</a>
<a href="https://www.techlifediary.com/p/privacy-policy.html">Privacy</a>
<a href="https://www.techlifediary.com/category/php/">Programming</a>
Now Create a index.php file to add the content.
<html>
<title>HomePage</title>
<body>
<?php include('header.php'); ?>
</body>
</html>
After including the Page into index.php will like this Image.
require() function
Using require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.
Now take an example without using a file we are going to use require() function.
<html>
<title>HomePage</title>
<body>
<?php require('invalidfile.php'); ?>//file not in the source
</body>
</html>
This will Happen when require() function will be used if the file will not available at the source.
Use requires when the file is required by the application.
Use includes when the file is not required and the application should continue when the file is not found.