Open In App

Difference between require() and require_once() in PHP

Last Updated : 21 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

PHP require() Function: The require() function in PHP is mostly used to include the code/data of one PHP file to another file. During this process, if there are any kind of errors then this require() function will display a warning along with a fatal error which will immediately stop the execution of the script. 

In order to use this require() function, we will first need to create two PHP files.  Include one PHP file into another one by using the include() function. The two PHP files are combined into one HTML file. This require() function will not see whether the code is included in the specified file before, rather it will include the code as many times the require() function is used.

Example:

HTML




<html>
  
<body>
    <h1>Welcome to geeks for geeks!</h1>
    <p>Myself, Gaurav Gandal</p>
  
    <p>Thank you</p>
  
    <?php require 'requiregfg.php'; ?>
</body>
  
</html>


 

requiregfg.php




<?php
  
    echo "<p>visit Again-" . date("Y"
        . " geeks for geeks.com</p>";
  
?>


Output:

PHP require_once() Function: The require_once() function in PHP is used to include one PHP file into another PHP file. It provides us with a feature that if a code from a PHP file is already included in a specified file then it will not include that code again if we use the require_once() function. It means that this function will add a file into another only once. 

In case this function does not locate a specified file then it will produce a fatal error and will immediately stop the execution.

Example:

PHP




<?php
    require_once('demo.php');
    require_once('demo.php');
?>


The following code is used in the above PHP code.

demo.php




<?php
    echo "Hello from Geeks for Geeks";
?>


Output:

Difference between require() and require_once():

                                    require()                                                 require_once()
The require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.
This function is mostly used where you want to include a certain code again and again. This function is mostly used where you want to include a certain code just once.
 Use require() to load template-like files. Use require_once() to load dependencies ( classes, functions, constants).
The require() function will execute every time it is called. The require_once() function will not execute every time it is called (It will not execute if the file to be included is included before)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads