[php] Difference between require, include, require_once and include_once?

In PHP:

  • When should I use require vs. include?
  • When should I use require_once vs. include_once?

This question is related to php include require require-once

The answer is


Require critical parts, like authorization and include all others.

Multiple includes are just very bad design and must be avoided at all. So, *_once doesn't really matter.


Whenever you are using require_once() can be use in a file to include another file when you need the called file only a single time in the current file. Here in the example I have an test1.php.

<?php  
echo "today is:".date("Y-m-d");  
?>  

and in another file that I have named test2.php

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

as you are watching the m requiring the the test1 file twice but the file will include the test1 once and for calling at the second time this will be ignored. And without halting will display the output a single time.

Whenever you are using 'include_once()` can be used in a file to include another file when you need the called file more than once in the current file. Here in the example I have a file named test3.php.

<?php  
echo "today is:".date("Y-m-d");  
?> 

And in another file that I have named test4.php

<?php  
include_once('test3.php');  
include_once('test3.php');  
?>

as you are watching the m including the test3 file will include the file a single time but halt the further execution.


An answer after 7 years for 2018

This question was asked seven years ago, and none of answers provide practical help for the question. In the modern PHP programming you mainly use required_once only once to include your autoloader class (composer autoloader often), and it will loads all of your classes and functions (functions files need to be explicitly added to composer.json file to be available in all other files). If for any reason your class is not loadable from autoloader you use require_once to load it.

There are some occasions that we need to use require. For example, if you have a really big array definition and you don't want to add this to your class definition source code you can:

 <?php
// arr.php
return ['x'=>'y'];

 <?php
//main.php
$arr= require 'arry.php'

If the file that you intend to include contains something executable or declares some variables you almost always need to use require, because if you use require_once apart from the first place your code will not be executed and/or your variables will not initiate silently, causing bugs that are absolutely hard to pinpoint.

There is no practical use case for include and include_once really.


My suggestion is to just use require_once 99.9% of the time.

Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

If you are require/including code that executes on the spot, that's procedural code, and you need to get to know a new paradigm. Like object oriented programming, function-based programming, or functional programming.

If you're already doing OO or functional programming, using include_once is mostly going to be delaying where in the stack you find bugs/errors. Do you want to know that the function do_cool_stuff() is not available when you go to call for it later, or the moment that you expect it to be available by requiring the library? Generally, it's best to know immediately if something you need and expect isn't available, so just use require_once.

Alternatively, in modern OOP, just autoload your classes upon use.


Difference between _once functions and without _once functions: without _once code will be included again whereas with _once functions PHP keeps track of the included files and will include it only once.

Difference between require and include: If a required file is not found PHP will emit a fatal error whereas for include only a warning will be emitted.


Use

  • require
    when the file is required by your application, e.g. an important message template or a file containing configuration variables without which the app would break.

  • require_once
    when the file contains content that would produce an error on subsequent inclusion, e.g. function important() { /* important code */} is definitely needed in your application but since functions cannot be redeclared should not be included again.

  • include when the file is not required and application flow should continue when not found, e.g.
    great for templates referencing variables from the current scope or something

  • include_once
    optional dependencies that would produce errors on subsequent loading or maybe remote file inclusion that you do not want to happen twice due to the HTTP overhead

But basically, it's up to you when to use which.


one thing I noticed, when using include I can only access the included files functions from the file that included it. With require_once, I can run that function in a second required_once file.

also: I recommend adding

if(file_exists($RequiredFile)){
    require_once($RequiredFile);
}else{
  die('Error: File Does Not Exist');
}

Because when require_once kills the page, it can sometimes echo the directory of your website files

Here's a custom function I made to require files:

function addFile($file, $type = 'php', $important=false){
    //site-content is a directory where I store all the files that I plan to require_once
    //the site-content directory has "deny from all" in its .htaccess file to block direct connections
    if($type && file_exists('site-content/'.$file.'.'.$type) && !is_dir('site-content/'.$file.'.'.$type)){
        //!is_dir checks that the file is not a folder
        require_once('site-content/'.$file.'.'.$type);
        return 'site-content/'.$file.'.'.$type;
    }else if(!$type && file_exists('site-content/'.$file) && !is_dir('site-content/'.$file)){
        //if you set "$type=false" you can add the file type (.php, .ect) to the end of the "$file" (useful for requiring files named after changing vars)
        require_once('site-content/'.$file);
        return 'site-content/'.$file;
    }else if($important){
        //if you set $important to true, the function will kill the page (which also prevents accidentally echoing the main directory path of the server)
        die('Server Error: Files Missing');
        return false;
    }else{
        //the function returns false if the file does not exist, so you can check if your functions were successfully added
        return false;
    }
}

usage example:

$success = addFile('functions/common');

if($success){
    commonFunction();
}else{
    fallbackFunction();
}

From the manual:

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

The same is true for the _once() variants.


You should keep class and function definitions organized in files.

Use require_once() to load dependencies (classes, functions, constants).

Use require() to load template-like files.

Use include_once() to load optional dependencies (classes, functions, constants).

Use include() to load optional template-like files.


It's often a matter of whether you want to load a client library conditionally, or go ahead and load it whether or not you're going to use it.

Here's concrete example; elaborating on what pcj said.

Say you have a configuration file storing your database username and password (conf.php):

<?php
//my site configuration file

//For Database
$location='localhost';
$dbuser='yourname';
$userpw='yourpassword';
$database='nameofdatabase';
?>

And a class with a static function that uses the database:

<?php
class UsedInLoop {
    public static function databaseQuery(){
        require(/path/to/conf.php);                //require_once will not work here
        $db = new mysqli($location, $dbuser, $userpw, $database);
        //yada yada yada
    }
}
?>

And that static function is used inside of another function that is being called iteratively inside a loop:

<?php
require_once('path/to/arbitraryObject.php');  //either will likely be OK at this level
$obj = new arbitraryObject();
foreach($array as $element){
    $obj->myFunction();
}
?>

You can only require/include the class once. If you require/include it on every iteration of your loop, you'll get an error. However, you have to include your conf file every time the static function is called.

<?php
class arbitraryObject {
    public function myFunction(){
        require_once(/path/to/UsedInLoop.php);   //This must be require_once. require() will not work
        UsedInLoop::databaseQuery();
    }
}
?>

Of course, moving it outside of the function could be a solution to that problem:

<?php
require(/path/to/UsedInLoop.php);   //now require() is fine   
class arbitraryObject {
    public function myFunction(){
        UsedInLoop::databaseQuery();
    }
}
?>

Unless you're concerned with the overhead of loading a class that might only be used in certain conditions and don't want to load it when it isn't.


  1. Use require function when you need to load any class, function, or dependency.

  2. Use include function when you want to load template-styled file

If you are still confused, just use require_once for all time.


I was using function as below:

function doSomething() {
    require_once(xyz.php);
    ....
}

There were constant values declared in xyz.php.

I have to call this doSomething() function from another PHP script file.

But I observed behavior while calling this function in a loop, for first iteration doSomething() was getting constant values within xyz.php, but later every iteration doSomething() was not able to get the constant values declared in xyz.php.

I solved my problem by switching from require_once() to include(), updated doSomething() code is as below:

function doSomething() {
    include(xyz.php);
    ....
}

Now every iteration call to doSomething() gets the constant values defined in xyz.php.


require has greater overhead than include, since it has to parse the file first. Replacing requires with includes is often a good optimization technique.


include() will generate a warning when it doesn't find a file, but require_once() will generate a fatal error.

Another thing is if file is included before. Then require_once() will not include it again.


 

  1. When should one use require or include?

    The require and include functions do the same task, i.e. includes and evaluates the specified file, but the difference is require will cause a fatal error when the specified file location is invalid or for any error whereas include will generate a warning and continue the code execution.

    So you may use the require function in the case where the file you are trying to include is the heart of the system and may cause a huge impact on rest of the code and you can use the include function when the file you are trying to include is a simple file containing some less important code.

    And my personal recommendation (for less important code) is to go for the require function everywhere in your code while it is in development phase such that you can debug code and later on replace all require functions by include function before moving it to production such that if you miss any bugs it will not affect the end user and the rest of the code executes properly...

  2. When should one use require_once or require?

    The basic difference between require and require_once is require_once will check whether the file is already included or not if it is already included then it won't include the file whereas the require function will include the file irrespective of whether file is already included or not.

    So in cases where you want to include some piece of code again and again use the require function whereas if you want to include some code only once in your code, use require_once.


In the age of PSR-0 / PSR-4 autoloaders, it may be completely unnecessary to use any of the statements if all you need is to make some functions / classes available to your code (of course, you still need to require_once autoloader itself in your bootstrap file and include templates if you still use PHP as a template engine).


Basically, if you require a wrong path, PHP throws a fatal error and the shutdown function is called, but when you include a wrong path, PHP will continue execution, but it will just display a warning that the file does not exist.

From the English word require, PHP is told that the execution of the page or file depends on the file required.

From my experience, it's norm to require important files such as configuration files, database classes and other important utilities.


include() will throw a warning if it can't include the file, but the rest of the script will run.

require() will throw an E_COMPILE_ERROR and halt the script if it can't include the file.

The include_once() and require_once() functions will not include the file a second time if it has already been included.

See the following documentation pages:


Just use require and include.

Because think how to work with include_once or require_once. That is looking for log data which save included or required PHP files. So that is slower than include and require.

if (!defined(php)) {
    include 'php';
    define(php, 1);
}

Just using like this...


The difference is in the error the commands generate. With require, the file you want to use is really required and thus generates an E_ERROR if it is not found.

require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error.

include only generates an E_WARNING error if it fails which is more or less silent.

So use it if the file is required to make the remaining code work and you want the script to fail the file is not available.


For *_once():

include_once() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

Same applies to require_once() of course.


Reference: require(), include_once()


Use "include" for reusable PHP templates. Use "require" for required libraries.

"*_once" is nice, because it checks whether the file is already loaded or not, but it only makes sense for me in "require_once".


They are all ways of including files.

Require means it needs it. Require_once means it will need it but only requires it once. Include means it will include a file but it doesn’t need it to continue.

Examples:

Require 'filename'
Require_once 'filename'
Include 'filename'

There is also an include_once function which includes a file once.

Include_once 'filename'

Don’t use capital letters where I have as I am typing from my phone.


With require the file must exist, if it doesn't then an error will display; whereas with include - if the file doesn't exist then then the page will continue loading.


Include / Require you can include the same file more than once also:

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

require_once / include_once

is identical to include/require except PHP will check if the file has already been included, and if so, not include (require) it again.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to include

"Multiple definition", "first defined here" errors Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 Include PHP file into HTML file Cannot open include file with Visual Studio How to make Apache serve index.php instead of index.html? Include php files when they are in different folders Already defined in .obj - no double inclusions What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files? What is the correct syntax of ng-include? Visual Studio can't 'see' my included header files

Examples related to require

The difference between "require(x)" and "import x" PHP - Failed to open stream : No such file or directory cannot redeclare block scoped variable (typescript) NodeJs : TypeError: require(...) is not a function Include PHP file into HTML file How to make node.js require absolute? (instead of relative) Ruby 'require' error: cannot load such file Nodejs cannot find installed module on Windows is there a require for json in node.js node.js require all files in a folder?

Examples related to require-once

relative path in require_once doesn't work Difference between require, include, require_once and include_once?