PHP 8 - Include/Require

Last modified: April 02, 2022
PHP Include & PHP Include_once

"include" and "include_once" throw a warning and the execution continues

PHP Require & PHP require_once

"require" and "require_once" throw a fatal error if the file is not existing and stop the script execution

Let's an example, we are going to build a Website using PHP. There are common items in the layout e.g. menu header, footer. We need menu header on all pages, instead of repeated menu header code on each of pages, we create a PHP called header.php and include in each pages of Website. In event of changes happen to header.php, we can just update one file rather than on each pages of Website.

<?php <a href="/home">Home</a> <a href="/service">Service</a> <a href="/contact">Contact us</a> ?>

In each pages of Website, we simply add this

<?php include 'header.php'; ?>
<?php require "header.php"; // this will include the header include_once "header.php"; // this will not as it was included using "require" require_once "header.php"; // this will not as it was included using "require" ?>