Difference Between Include and Require in PHP

One of the most frequently asked questions by people who are just learning PHP is, Why are there 4 ways to include a file on your web page?

There are include(), include_once(), require(), require_once()

What’s the difference? When is it used?

In this short article we will briefly know what each is used for.

Include function
The Include function is used in PHP when we want to include a file into the currently running process. It takes one argument which will be a string to the path of the file you want to include.

include “main_page.php”;
The code in the included file will be executed when the Include function is called.

It can be used in a PHP template system where you have many sections such as, header, sidebar, and footer.

include “header.php”;

include “footer.php”;
The header will be the header for the entire web page, as well as the sidebar and footer.

An error message will appear if the included file is not found.

PHP include_once Function
The Include_once function is almost the same as the Inlcude function, but will limit the files that will only be used once.

The Include function will allow you to include the same file multiple times so you can use it in a loop.

foreach($products as $product){

Will show all products

include “product.php”;
}
BUT, with include_once you will only display the product.php file once.

foreach($products as $product){

Will show one product

include_once “product.php”;
}
Another benefit of Include once is that if you define a function in the included file, it avoids redefining the function.

Require
The Require function works like the Include function, but if the file is not found it will throw a PHP Error. This function is required for the application to work properly.

require_once “main_page.php”;
This will be a Fatal error E_COMPILE_ERROR which will stop the application from running, where the include function will only generate an error message but will not stop the application, but will continue.

Require_Once
The last one is the Require_once Function, which is a combination of the Require and Include_once functions. This will ensure that the file exists before adding it to the page, otherwise it will raise a Fatal Error. Plus it will ensure that the file will only be used once on the web page.

require_once “header.php”;

require_once “sidebar.php”;

require_once “footer.php”;
This function is the most restrictive of these 4 functions, and it is usually preferred in building web pages.

That’s a short article this time.
Hopefully it can be useful for you