By Scott B


2010-03-10 16:13:25 8 Comments

In PHP:

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

25 comments

@Adam Winter 2020-05-12 18:41:52

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.

@PHPst 2017-11-11 00:00:05

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.

@haz 2018-06-25 04:13:35

+1 for mentioning the autoloader. However that last sentence is disputable. Quite often a you'll use an include(),wrapped in an output buffer to implement your templating engine.

@haz 2018-06-25 04:14:21

Also, given modern text editors and modern PHP, almost no-one uses require() to split large files.

@Youssef 2018-10-27 10:43:28

I faced the same issue when using require_once for PHPMailer inside a function, and my autoloader defines the $mail variable needed later in the code, so the next require_once gets ignored, which left $mail not initialized ! the solution was to simply use require after the function call.

@PHPst 2018-10-27 22:23:44

@haz Is there any reason you don't use require in those cases?

@PHPst 2019-11-09 05:17:29

@ChristofferBubach LOL.

@SwiftNinjaPro 2019-04-10 20:23:05

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();
}

@Leo 2010-03-10 16:17:52

There are require and include_once as well.

So your question should be...

  1. When should I use require vs. include?
  2. When should I use require_once vs. require

The answer to 1 is described here.

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

The answer to 2 can be found here.

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

@dialex 2012-08-27 14:21:21

Mind that require() executes faster than require_once(), so if you're sure there are no duplicated includes use require().

@Prof. Falken contract breached 2013-03-05 12:20:32

@DiAlex, require_once is slower, but almost not measurable.

@Tom 2013-04-20 22:36:33

@DiAlex ...and, if it turns out that the file is, in fact, already included, then require_once() will be the faster of the two

@Weishi Zeng 2014-10-14 04:53:26

@Prof.Falken Under what circumstances need one require same file more than once?? I can't think of one within my current mind set.

@Prof. Falken contract breached 2014-10-14 08:15:06

@WeishiZeng I never thought of any reason before either... but when you asked, what if the code required does not only define functions and constants, but also executes code? But this is not good programming practice.

@Weishi Zeng 2014-10-17 23:37:27

@Prof.Falken That could be one case right? But there should be other major reasons for it to make sense.

@Gui Imamura 2015-05-02 03:26:09

Maybe the file required is also required by another file that's included/required?

@jbolanos 2015-08-20 17:45:22

In a large code base, its possible to require/include a config file in multiple places either for testing or for reuse. by using _once you are avoiding it from biting you in the ass.

@Craig 2015-11-01 08:15:07

...which leads one to wonder why PHP, given the lengths it goes to in order to make so many other things automatic, doesn't just use the _once behavior as its default.

@jessica 2016-02-29 17:24:01

How about just not including the same files twice? The include() function will warn you when you include the same files twice.

@ReverseEMF 2016-04-21 16:50:38

The reason to have both require/include and require_once/include_once is to provide "performance diversity". If only 'require_once' existed, then the choice to use the [perhaps] faster 'require' would not exist. Regarding the question of "when would one need to require more then once?", think of a large scale development effort involving multiple teams. Very hard to keep that coordinated. The ability to 'require_once' eliminates one degree of complexity in what can be a logistic nightmare. Anyone who has worked in such an environment knows the level of coding standard compliance ;) .

@James Beninger 2016-07-07 22:32:41

@WeishiZeng for web pages, there may be HTML snippets that you want to include more than once.

@TheCrazyProfessor 2017-01-01 08:58:57

What about: use vs include vs require. When is it better to use: use instant of require?

@xDaizu 2017-07-04 09:48:22

@JamesBeninger ...because lets remember that PHP is (was?), after all, a templating language. Nowadays, in most cases, one shouldn't use require/include to execute code or as a template block (goosebumps)

@PHPst 2017-11-11 00:02:59

@WeishiZeng Please see my answer for this

@McAuley 2018-12-18 23:10:52

@ReverseEMF I'm late to the party on this, but I have PHP code in a number of my included (or required files). It appears that when I 'require_once" or 'include_once', then the results of a previous "click" seem to remain the same, e.g., if I typed "56.49" in a field and get an error popup (becuz that amount is greater than a maximum amount, for example), and then I change the field to be "55.00", I still get the "56.49" in my code. I can see it in the console. Is it possible that "require_once" is causing this, or should I be looking elsewhere. Haven't tracked it down yet.

@JSG 2019-08-11 20:28:02

@McAuley Im sure you figured it out by now, but if you include a server file that updates session variables( or variables period ) to be used multiple times in a completed script (from start to finish) then yes. It wont include or require the file if it has already been included leaving your variables the same as the first include_once or require_once.

@Tiberiu-Ionuț Stan 2012-06-02 09:20:26

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.

@Joshua Charles Pickwell 2017-11-22 08:20:47

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.

@mp31415 2015-10-25 15:39:26

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).

@Bink 2012-11-14 19:52:54

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

@ahouse101 2014-05-30 17:07:58

I know it's a late comment, but this is actually not true. require doesn't parse the file any more than include does. The _once versions of those functions each has a bit of overhead, but like others have said, it's close to negligible in most applications.

@Akshay Khale 2015-07-30 06:05:36

 

  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.

@Ruke GiPyeong Lee 2015-08-06 08:44:14

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...

@pcj 2016-09-30 06:51:28

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.

@Rotimi 2017-09-17 10:20:26

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.

@Kzqai 2010-03-10 16:46:47

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.

@Mark Amery 2013-06-25 10:01:17

+1 This should be the accepted answer. The key points are that the include family are usually an outright bad idea (because it's pretty rare to be including files that have any possibility of not existing), and that out of require_once and require, you should use require_once when including files that define functions or classes to be used elsewhere, or instantiate singletons like database connection objects, and use require for including files that immediately do stuff when they get included. In any large web application, the latter kind of include is unusual.

@James 2014-11-03 03:51:32

+1 (have another gold badge ;) ) Agree that sensibly require_once is most likely candidate to be used nearly all of the time. Given tiny overhead differences between the choices, require ensures script stops, I cannot think of many scenarios where an application can survive without a file being included. And _once protects from dupe issues. Anyone who disagrees likely knows what they're doing so can choose whichever suits the application or scenario.

@Ravinder Payal 2015-10-08 08:02:01

hey i have a file which is sometimes included in index page and man time called directly (home.php) ........... now i already included config file on index page with require function now can i use require_once in home.php to prevent re includes

@Kzqai 2015-10-09 17:49:54

@RavinderPayal Well, my first advice is to save yourself a headache by using a front-controller! Just because a user calls example.com/home doesn't mean you should have a totally separate home.php! Instead /home/ should just route through the front controller of index.php or front.php. Only php really allows for the oldschool "one script per page" approach any more, and trust me, it's not the best way. But if you MUST have a separate home.php and index.php, then anything that MAY GO IN BOTH should be in a library file or template, ../templates/home.tpl or ../view/home.view.php you know?

@Ravinder Payal 2015-10-10 10:44:05

its SNS and i choose one file one page approach initially for easy development and its a large stack of files which i cant recreate and now i solved that problem and the other reason of doing one file one page is speed and less contact with hard disk by decreasing number of includes

@Ömer An 2018-12-29 19:50:46

i changed my include to require_once on all pages of my website, let's see if i will have any trouble soon.

@Richard Smith 2019-05-14 13:25:16

The advice given in this answer is very good, but it would be significantly better if explained what the four options do, as @Gordon's answer above does.

@Gordon 2010-03-10 16:25:59

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.

@Shafizadeh 2016-04-26 19:25:35

I have a PDO-connection (to database). Should I use which one? include? include_once? require? require_once?

@Daniel W. 2016-05-06 15:45:12

This should be the accepted answer as it answers the question in short and links to the official manual, instead of the other answer only linking w3schools.

@Francisco Ochoa 2016-05-10 13:12:51

give me a reason why would you include it if it's not necessary?

@James Coyle 2017-08-23 15:41:03

I'm using a template for a generic page layout that has sections such as headers, columns, footers etc. This allows me to serve that template for every page on the site and I only need to create files in the page folder structure defining what should go into each of those positions. If I decide that a page doesn't need a sidebar I just leave out that file in the folder for that page and the template still works just fine without that file existing.

@James Wong 2015-07-07 04:13:21

  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.

@Polynomial 2011-11-03 11:48:14

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:

@Rukmi Patel 2011-11-03 11:48:37

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.

@mo. 2010-03-10 17:08:38

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".

@Your Common Sense 2010-03-10 17:04:30

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.

@AliMohsin 2012-09-29 09:42:35

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.

@Ramesh Kithsiri HettiArachchi 2018-01-01 07:27:43

'example better than advice'

@Marcx 2011-11-03 11:48:24

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.

@Ferdinand Beyer 2011-11-03 11:46:19

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.

@Felix Kling 2010-03-10 16:20:32

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()

@Yousha Aleayoub 2017-09-20 10:42:19

require gives E_COMPILE_ERROR, not E_ERROR.

@Felix Kling 2017-09-20 12:26:01

Looks like it changed in the last 7 years.

@Brian 2010-03-10 16:24:59

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.

@Sebastian 2010-03-10 16:18:14

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.

@Vlad 2019-02-09 13:04:39

Wow short and simple!

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

38 Answered Questions

[SOLVED] Deleting an element from an array in PHP

  • 2008-12-15 20:28:55
  • Ben
  • 2627890 View
  • 2513 Score
  • 38 Answer
  • Tags:   php arrays unset

23 Answered Questions

[SOLVED] When to use self over $this?

  • 2008-09-30 06:23:06
  • Casey Watson
  • 700440 View
  • 1997 Score
  • 23 Answer
  • Tags:   php class oop scope

10 Answered Questions

[SOLVED] What is the difference between #import and #include in Objective-C?

28 Answered Questions

11 Answered Questions

[SOLVED] What is the difference between include and require in Ruby?

17 Answered Questions

[SOLVED] What is the difference between public, private, and protected?

4 Answered Questions

[SOLVED] Include, require & require_once

Sponsored Content