php[tek] 2018 : Call for Speakers

require_once

(PHP 4, PHP 5, PHP 7)

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.

See the include_once documentation for information about the _once behaviour, and how it differs from its non _once siblings.

add a note add a note

User Contributed Notes 23 notes

up
98
bimal at sanjaal dot com
6 years ago
If your code is running on multiple servers with different environments (locations from where your scripts run) the following idea may be useful to you:

a. Do not give absolute path to include files on your server.
b. Dynamically calculate the full path (absolute path)

Hints:
Use a combination of dirname(__FILE__) and subsequent calls to itself until you reach to the home of your '/index.php'. Then, attach this variable (that contains the path) to your included files.

One of my typical example is:

<?php
define
('__ROOT__', dirname(dirname(__FILE__)));
require_once(
__ROOT__.'/config.php');
?>

instead of:
<?php require_once('/var/www/public_html/config.php'); ?>

After this, if you copy paste your codes to another servers, it will still run, without requiring any further re-configurations.

[EDIT BY danbrown AT php DOT net: Contains a typofix (missing ')') provided by 'JoeB' on 09-JUN-2011.]
up
2
apis17
9 days ago
require_once may not work correctly inside repetitive function when storing variable for example:

file: var.php
<?php
$foo
= 'bar';
?>

file: check.php
<?php

function foo(){
    require_once(
'var.php');
    return
$foo;
}

for(
$a=1;$a<=5;$a++){
    echo
foo()."<br>";
}

>
php check.php
result
:
bar
<empty line>
<empty
line>
<empty
line>
<empty
line>

to make sure variable bar available at each function call, replace require once with require. eg situation: https://stackoverflow.com/questions/29898199/variables-not-defined-inside-function-on-second-time-at-foreach

Solution:

file: check2.php
<?php

function foo(){
    require(
'var.php');
    return
$foo;
}

for(
$a=1;$a<=5;$a++){
    echo
foo()."<br>";
}

>
php check2.php
result
:
bar
bar
bar
bar
bar
up
13
powtac at gmx dot de
2 years ago
"require_once" and "require" are language constructs and not functions. Therefore they should be written without "()" brackets!
up
-17
Konstantin Rozinov (krozinov[at]gmail)
8 years ago
There's been a lot of discussion about the speed differences between using require_once() vs. require().
I was curious myself, so I ran some tests to see what's faster:
- require_once() vs require()
- using relative_path vs absolute_path

I also included results from strace for the number of stat() system calls.  My results and conclusions below.

METHODOLOGY:
------------
The script (test.php):
<?php
$start_time
= microtime(true);
   
/*
  * Uncomment one at a time and run test below.
  * sql_servers.inc only contains define() statements.
  */

//require ('/www/includes/example.com/code/conf/sql_servers.inc');
//require ('../../includes/example.com/code/conf/sql_servers.inc');
//require_once ('/www/includes/example.com/code/conf/sql_servers.inc');
//require_once ('../../includes/example.com/code/conf/sql_servers.inc');

$end_time = microtime(true);

$handle = fopen("/tmp/results", "ab+");
fwrite($handle, ($end_time - $start_time) . "\n");
fclose($handle);
?>

The test:
  I ran ab on the test.php script with a different require*() uncommented each time:
  ab -n 1000 -c 10 www.example.com/test.php

RESULTS:
--------
The average time it took to run test.php once:
require('absolute_path'):      0.000830569960420
require('relative_path'):      0.000829198306664
require_once('absolute_path'): 0.000832904849136
require_once('relative_path'): 0.000824960252097

The average was computed by eliminating the 100 slowest and 100 fastest times, so a total of 800 (1000 - 200) times were used to compute the average time.  This was done to eliminate any unusual spikes or dips.

The question of how many stat() system calls were made can be answered as follows:
- If you run httpd -X and then do an strace -p <pid_of_httpd>, you can view the system calls that take place to process the request.
- The most important thing to note is if you run test.php continuously (as the ab test does above), the stat() calls only happen for the first request:

  first call to test.php (above):
  -------------------------------
  lstat64 ("/www", {st_mode=S_IFDIR|0755, st_size=...
  lstat64 ("/www/includes", {st_mode=S_IFDIR|0755,...
  lstat64 ("/www/includes/example.com", {st_mode=S...
  lstat64 ("/www/includes/example.com/code", {st_m...
  lstat64 ("/www/includes/example.com/code/conf", ...
  lstat64 ("/www/includes/example.com/code/conf/sql_servers.inc", {st_mode...
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17
 
  subsequent calls to test.php:
  -----------------------------
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

- The lack of stat() system calls in the subsequent calls to test.php only happens when test.php is called continusly.  If you wait a certain period of time (about 1 minute or so), the stat() calls will happen again.
- This indicates that either the OS (Ubuntu Linux in my case), or Apache is "caching" or knows the results of the previous stat() calls, so it doesn't bother repeating them.
- When using absolute_path there are fewer stat() system calls.
- When using relative_path there are more stat() system calls because it has to start stat()ing from the current directory back up to / and then to the include/ directory.

CONCLUSIONS:
------------
- Try to use absolute_path when calling require*().
- The time difference between require_once() vs. require() is so tiny, it's almost always insignificant in terms of performance.  The one exception is if you have a very large application that has hundreds of require*() calls.
- When using APC opcode caching, the speed difference between the two is completely irrelevant.
- Use an opcode cache, like APC!

Konstantin Rozinov
krozinov [at] gmail
up
-19
miqrogroove
12 years ago
require_once() is NOT independent of require().  Therefore, the following code will work as expected:

echo.php
<?php
echo "Hello";
?>

test.php
<?php
require('echo.php');
require_once(
'echo.php');
?>

test.php outputs: "Hello".

Enjoy,
-- Miqro
up
-21
Dodo
3 years ago
If you happen to encounter some "Warning: require_once(): failed to open stream" and you are certain the provided path is right, consider the following example & solution.

Considering the following tree:
+ C:\server\absolute\path\
    + somefolder\
        - index.php
    + supbath
        + anotherfolder1\
            - file1.php
            - file2.php
        + anotherfolder2\
            - file3.php

With the respective sources:
original index.php:
<?php

   
// absolute path
    // inclusion status: SUCCESS
   
require_once 'C:\server\absolute\path\subpath\anotherfolder1\file1.php';

?>

original file1.php:
<?php

   
// relative path
    // inclusion status: SUCCESS
   
require_once 'file2.php';

   
// relative path
    // inclusion status: FAILURE
   
require_once '../anotherfolder2/file3.php';

?>

You will notice the use of "\" as DIRECTORY_SEPARATOR, but the same result is obtained using "/".
Assumption ? PHP does not behave as it should if it encounters a relative path starting by a '../'. Well, this is not true.

Below is a modified file1.php:
<?php

   
// absolute path
    // inclusion status: SUCCESS
   
require_once '/file2.php';

   
// absolute path
    // inclusion status: SUCCESS
   
require_once '/../anotherfolder2/file3.php';

?>

It seems that PHP recognizes a non-prefixed file name as an absolute path in a require_once, and that it computes this absolute path from a relative context.

I am not sure this is the expected behaviour, but it was quite hard to figure out. Also, if you want to recognize those special cases where you had to specify a relative path starting with a "/", you can use the following trick.

<?php

   
// it goes down one level, and then goes up one level : the result is neutral, but after prefixing your paths with this, PHP handles them
   
define ('REQUIRE_TRICK', '/TRICK/../');

    require_once
REQUIRE_TRICK . 'file2.php';
    require_once
REQUIRE_TRICK . '../anotherfolder2/file3.php';

?>

If this ever gets reworked/fixed, it will be easy to remove the define.
up
-17
jason semko at gmail dot com
7 years ago
If you are coding on localhost and require_once is not opening files due to 'relative paths' a simple solution is:

<?php

     
require_once(dirname(__FILE__) . "/file.php");

?>

If you have file.php under the folder 'includes' (or anywhere for that matter), then folder 'public' AND folder 'public/admin' will be able to access all required files despite having different relative paths.
up
-15
spark at limao dot com dot br
6 years ago
if you use require_once on a file A pointing to file B, and require_once in the file B pointing to file A, in some configurations you will get stuck

also wouldn't it be nice to manage that to prevent getting stuck AND use the good old Java import?

<?php
      
function import($path=""){
               if(
$path == ""){ //no parameter returns the file import info tree;
                      
$report = $_SESSION['imports'];
                       foreach(
$report as &$item) $item = array_flip($item);
                       return
$report;
               }

              
$current = str_replace("\\","/",getcwd())."/";
              
$path = $current.str_replace(".","/",$path);
               if(
substr($path,-1) != "*") $path .= ".class.php";

              
$imports = &$_SESSION['imports'];
               if(!
is_array($imports)) $imports = array();

              
$control = &$imports[$_SERVER['SCRIPT_FILENAME']];
               if(!
is_array($control)) $control = array();

               foreach(
glob($path) as $file){
                      
$file = str_replace($current,"",$file);
                       if(
is_dir($file)) import($file.".*");
                       if(
substr($file,-10) != ".class.php") continue;
                       if(
$control[$file]) continue;
                      
$control[$file] = count($control);
                       require_once(
$file);
               }
       }
?>

just remember to start the session and to enable the glob function

now you can use
<?php
    import
("package.ClassName");
   
import("another.package.*"); //this will import everything in the folder
?>
up
-12
thomas dot revell at uwe dot ac dot uk
12 years ago
Regarding the case insensitivity problems on Windows, it looks to me as though it is a problem in PHP5 as well (at least in some cases).

The following gave me problems:

From file URLSwitcher.php
<?php
require_once 'slimError/slimError.php';
require_once
'Navigator_Cache.php';
....
?>

From file Navigator_Cache.php
<?php
require_once 'slimError/slimerror.php';
...
?>

From file slimerror.php
<?php
class SLIMError {
...
}
?>
The above setup gave me an error : "Cannot redeclare class SLIMError"

If I change the require_once in URLSwitcher.php to match the one in Navigator_Cache.php, there isn't a problem, but if I do this the other way round, the same problem occurs.
up
-21
jazfresh at hotmail.com
10 years ago
Check how many files you are including with get_required_files(). If it's a significant number (> 100), it may be worth "compiling" the main PHP file. By "compiling", I mean write a script that reads a PHP file and replaces any "include/require_once" references with either:
- the file that it's requiring
- a blank line if that file has been included before

This function can be recursive, thus building up a large PHP file with no require_once references at all. The speedup can be dramatic. On one of our pages that included 115 classes, the page was sped up by 60%.
up
-15
ivan[DOT_NO_SPAM]chepurnyi[AT]gmail
8 years ago
Also if you have a large MVC framework, it make sense to compile  structure "file/path/to/class.php" to something like this "file_path_to_class.php", it will speed up any type of php files includes, becouse php interpreter will not check FS stat data for directories "file", "file/path", "file/path/to", etc.
up
-17
amcewen at look dot ca
9 years ago
Perhaps it would be clearer to say that require_once() includes AND evaluates the resulting code once.  More specifically, if there is code in the script file other than function declarations, this code will only be executed once via require_once().
up
-14
Pure-PHP
12 years ago
require_once can slower your app, if you include to many files.

You cann use this wrapper class, it is faster than include_once

be execd_ser12ss="da href="htt().
1/span> 2/span>
down
-12
ivan[DOT_NO_Snci szlng> &par11733ass=iv class="date" title="2015-09-02 01:36">5-22ong>3 years ago
require_once
exactng wit.&nbooback up to . Soeed upom, bmiredcode i info tsequer: You cann usecod(!n>
<403ass="/manual/vote-note.php?id=115287&pag403anction.require-once&vote=up" title="V"Vote down!" class="usernotes-voted">down
-12
8
amcewen at lo#81loct com &par11403ass=iv class="date" title="2014-06-28 10:41">1">< 09:43years ago
If you are cote iskingAsusedpt fas fastercare clb if y folandlire-once (e thiawarrequirig standles i.e.ir />Asiferentr
arationstedbad practice). Howwork,ed 115 csp; Trecursrer t MVC sMVCd : "
<08lass="/manual/vote-note.php?id=51044&pag08lanction.require-once&vote=up" title="V"Vote down!" class="usernotes-voted">down
-12
ivan[DOT_NO_jtaa ac deljaki> &parv08lass=iv class="date" title="2005-03-17 02:19">12 years ago
If you are cPC oprecofeep (he)nhpitefor
- an> <_ todce ouuire-onc, t ma'ed beh
<?php

&class="comment">//this will im /varreqe/app//becau/any filehicr />With the res class="keyword">);
import- an> <_ todce o class="keyword">($control('/TRERVER) . '/TRERVER(
$pather.pack/^(.+)\/[^\/]+$an class="keyword">,'/TRERVER) . '/TRERVER))
'/TRERVER= array(); $pather.paclan class="keyword">= aERVER)) $filen class="keyword">) != ] class="default">$pather.pac/ class="default">$control('/TRERVER= array();
'/TRERVER($pather.pack\nn class="keyword">,'/TRERVER)) '/TRERVER($control)) &class="comment">//this will im efine.'/TRbr />glob<$lan class="keyword">= array(); $file) . $file) . ?>

test.php outTha ann><?php

>&class="comment">//this will im /varreqe/app/ page wehicr />With the res class="keyword">);
'echo.php'n class="keyword">);
?>

- an> <_ todce o class="keyword">(
$cother.pack page w/*n class="keyword">,'/TRERVER) .
?>

If you have Tha (*)des, beco fola/spank up to / page w s witutomaghere iith getedpr />Asbr />- an> <_ todce o>The following it'sbr />
As (at iursrmbinTrecurwecti page w s up onitutololeofeaath/>The followin--llowinJaap Taa de>
If you are cPectibowit.&n you uire-oncs guyes t&nbetlude_ocasesitua-once OK,/SOME MAY DISPUTEed 115r />Asi

once in the file "cosbspvel, a>aath/, DIEn>Asfew INCLUDESs anyR oame p>Be>
<246ass="/manual/vote-note.php?id=73733&pag246anction.require-once&vote=up" title="V"Vote down!" class="usernotes-voted">down
-21
8
ivan[DOT_NO_sneskidcom
&parv246ass=iv class="date" title="2007-03-07 11:22">1-19 12>12 years ago
If you are c"default"><?php
class import);
&nbn class="default">$report
,$imports) . $report[$file= array(); $filen>(__FILE__,"/");

str_replace<= array(); <) ) );n>import) . $report ,$imports) . $report);
&nbn class="default">$report
,$imports) . $report['REQports) . $report);
&nb;n>import) . $report ,$imports) . $report);
&nbn class="default">$report
,$imports) . n class="string">'REQports) . $report);
&nb;n>import($file,$imports) . $report);
&nbn class="default">$report
,$imports) . 'REQports) . $report);
&nb;n>import($file,$imports) . $report);
&nbn class="default">$report
,$imports) . >$file) . $report);
&nb;n>import($file,$imports) . $report);
&nbn class="default">$report
,$imports) . $file) . $report);
&nb;n>?>

If you have I fme pAsnot r">The followin"default"><?php
clahis will i*>The foRs.aration>The fo*/>class import) . $report ) . '/TRo.php'
);
?>

test.php outIt by 6easn utemodifytoncer to panan[ful f re io tin/any fileThe followin"default"><?php
clahis will i*> ,uppro en>Asnot rbmirecludewecti@e resuted wnclud i info doesy staexisa hp outSt any howsp; strucsnot r"/wari()., unle"The foRs.aration>The fo*/>claort($filenn>) . '/TRo.php'
);
?>

test.php outIe to mcted:wectia deep cludes, file/path/toncea bspanges in evaluate" refers/es, -lole a classtedeast i>Be>
69339ss="/manual/vote-note.php?id=115287&p69339nction.require-once&vote=up" title="V"Vote down!" class="usernotes-voted">down
-17
ivan[DOT_NO_rejjnt coma/s> &par69339ss=iv class="date" title="2005-03-17 02:16">9-0rong>28years ago
n>downdow'&wedth='12' height='12'>ss=mall>addea >dowBe>mall>ss="d> ee-onc>
ee-onc>