PHP Include File
You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function.
The two functions are identical in every way, except how they handle errors. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).
These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages. This can save the developer a considerable amount of time.
This means that you can create a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all web pages).
The include() Function:
The include() 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 include() function generates a warning but the script will continue execution.
<?php include('header.php') ?>
The require() Function:
The 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.
<?php require ('header.php') ?>
Difference Between include and require Statements
You might be thinking if we can include files using the include() statement then why we need require(). Typically the require() statement operates like include().
The only difference is — the include() statement will only generate a PHP warning but allow script execution to continue if the file to be included can't be found, whereas the require() statement will generate a fatal error and stops the script execution.
The include_once and require_once Statements
If you accidentally include the same file (typically functions or classes files) more than one time within your code using the include or require statements, it may cause conflicts. To prevent this situation, PHP provides include_once and require_once statements. These statements behave in the same way as include and require statements with one exception.
The include_once and require_once statements will only include the file once even if asked to include it a second time i.e. if the specified file has already been included in a previous statement, the file is not included again.