What are the differences between require and include?

There are following difference between require and include.

  1. require will produce a fatal error and stops the script
  2. include will only produce a warning and the script will continue.

PHP include Function

The include function is used in PHP when you want to include a file with in the process. It takes one argument which contains string to the file path you want to include.

include 'page.php';

The code inside the included file will run when the include function is called.

In PHP sites, normally header and footers are same on all the pages of sites. In that case we use include function to add the file to the page.

include 'header.php'; 
<div id="content">
      // content data
</div> 
include 'footer.php';

If the file that you are includes is not found then this function return a PHP warning, which is different from require function which will return a fatal error.

PHP include_once Function

The include_once function is exactly the same as the include function except it will limit the file that it can be used only once in a page.

include_once 'page.php';

The include function will allow to include the same file multiple times so we can use it within a loop.
For example:

foreach($products as $product)
{
    // will display all products.php
    include 'product.php';
}

This will include the product.php file as many times as count of $products array, but if we use include_once function it will only display the product.php file once.

foreach($products as $product)
{
    // will only display one product
    include_once 'product.php';
}

PHP require Function

The require function acts like include function but if the file can not be found it will throw a PHP error.
It will throw a fatal error E_COMPILE_ERROR which will stop the application, where the include function will just return a warning but the application will continue.

The require function is used exactly the same as the include function.

require 'page.php';

PHP require_once Function

It is a combination of the require and include_once function.When file adding it to the page if it’s not there it will throw a fatal error. Plus it will make sure that the file can only be used once on the page.

This function is the strict function from the four functions. require_once function is use when displaying things like the website header and footer only once in page.

require_once 'header.php';

<div id="content">

</div>

require_once 'footer.php';

Leave a Reply

Your email address will not be published. Required fields are marked *

Do NOT follow this link or you will be banned from the site!