Php require file in different directory

There are several ways to achieve this.

Use relative path from form.php

require_once __DIR__ . '/otherfile.php';

If you're using PHP 5.2 or older, you can use dirname[__FILE__] instead of __DIR__. Read more about magic constants here.

Use the $_SERVER['DOCUMENT_ROOT'] variable

This is the absolute path to your document root: /var/www/example.org/ or C:\wamp\www\ on Windows.

The document root is the folder where your root level files are: //example.org/index.php would be in $_SERVER['DOCUMENT_ROOT'] . '/index.php'

Usage: require_once $_SERVER['DOCUMENT_ROOT'] . '/include/otherfile.php';

Use an autoloader

This will probably be a bit overkill for your application if it's very simple.

Set up PHP's include paths

You can also set the directories where PHP will look for the files when you use require[] or include[]. Check out set_include_path[] here.

Usage: require_once 'otherfile.php';

Note:

I see some answers suggest using the URL inside a require[]. I would not suggest this as the PHP file would be parsed before it's included. This is okay for HTML files or PHP scripts which output HTML, but if you only have a class definition there, you would get a blank result.

PHP Require File statement is identical Include File statement [except upon failure it will also produce a fatal E_COMPILE_ERROR level error].
Also, their syntax relative and absolute file paths are identical.

PHP Require File Statement

require 'myfile.php';

PHP require file from parental directory [folder] - relative path

require[dirname[__DIR__].'/../ myfile.php'];


PHP Require File from ROOT directory

require[$_SERVER['DOCUMENT_ROOT']."/myfile.php"];

PHP Require File deeper directory then ROOT - absolute path

$root = realpath[$_SERVER["DOCUMENT_ROOT"]];
require "$root/folder1/folder2/myfile.php";

[PHP 4, PHP 5, PHP 7, PHP 8]

The require_once expression 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.

bimal at sanjaal dot com

11 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:



instead of:


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

bobray99 at softville dot com

4 months ago

Be careful when using include_once and require_once for files that return a value:

fiddle2.php


and another file that is called "first.php" and write the following header

-------------------------------

Hello every one

--------------------------------

i hope this will help you

powtac at gmx dot de

7 years ago

"require_once" and "require" are language constructs and not functions. Therefore they should be written without "[]" brackets!

apis17

4 years ago

require_once may not work correctly inside repetitive function when storing variable for example:

file: var.php


file: check.php


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

Mental_Wanderer

4 years ago

Friendly reminder about namespaces...
Including or requiring a PHP file that defines as namespace means that the namespace name [or its "use ... as ..." alias] is always necessary to make use of the included file's content:

// A.php



// B.php

miqrogroove

17 years ago

require_once[] is NOT independent of require[].  Therefore, the following code will work as expected:

echo.php


test.php


test.php outputs: "Hello".

Enjoy,
-- Miqro

ivan[DOT_NO_SPAM]chepurnyi[AT]gmail

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

inci szlk

7 years ago

you can also use this type define to get exact path of root directory. So, it won't mess if the file is in whatever directory in whatever directory.

if [!defined["DOCUMENT_ROOT"]] define["DOCUMENT_ROOT", $_SERVER['DOCUMENT_ROOT']];

require_once DOCUMENT_ROOT.'/hello/world.php';

thomas dot revell at uwe dot ac dot uk

17 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


From file Navigator_Cache.php


From file slimerror.php

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.

jazfresh at hotmail.com

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

jason semko at gmail dot com

12 years ago

If you are coding on localhost and require_once is not opening files due to 'relative paths' a simple solution is:



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.

antoine dot pouch at mcgill dot ca

16 years ago

require_once [and include_once for that matters] is slow.
Furthermore, if you plan on using unit tests and mock objects [i.e. including mock classes before the real ones are included in the class you want to test], it will not work as require[] loads a file and not a class.

To bypass that, and gain speed, I use :



I tried to time 100 require_once on the same file and it took the script 0.0026 seconds to run, whereas with my method it took only 0.00054 seconds. 4 times faster ! OK, my method of testing is quite empirical and YMMV but the bonus is the ability to use mock objects in your unit tests.

amcewen at look dot ca

14 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[].

spark at limao dot com dot br

11 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?

Chủ Đề