PHP require & require_once

In this lesson, you will learn about require and require_once in PHP, their usage, and examples to better understand the topic.

PHP require and require_once

There are two differences in the require declaration: require and require_once. The declarations “require / require_once” are used for file inclusion and will halt the script’s execution if an error occurs. PHP require() function also includes a file in the PHP application. If your application requires the file, e.g., a significant message template or a file that contains configuration variables without which the application breaks, then use the ‘require’ declaration.

PHP require_once() function determines whether a file has already been included or not and only includes it if it hasn’t. Use require_once() if you need to include a file multiple times across various files.


<h1>Title of the page!</h1>
<?php require 'FileNotPresent.php';
echo "I have a $color $car.";


If the same example is performed using the include statement, PHP will execute the echo statement because the script execution won’t die after the include statement returns a warning.

PHP the include vs. require

Include statement gives a warning when an error comesRequire statement does not issue a warning when an error occurs
It doesn't stop the execution of the script; instead continues when an error occurs.It stops the execution of the script when an error occurs.
Use the include when the file is not required, and the application should continue when the file is not found.Use the require statement when the application requires the file.

It is generally advised to use the include statement so that the script will continue to execute in the event of an error. Use the ‘require’ statement if the complete script cannot run without the requested file. You can use the include and require statements in any source program code wherever you want the code to appear.

This concludes the PHP require & require_once lesson. In the next lesson, you will learn about PHP Session.