User Contributed Notes 22 notes

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.

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.

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.000830569960420require('relative_path'): 0.000829198306664require_once('absolute_path'): 0.000832904849136require_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:

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

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.

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 themdefine ('REQUIRE_TRICK', '/TRICK/../');

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.

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

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.

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

The path for nested require_once() is always evaluated relative to the called / first file containing require_once(). To make it more flexible, maintain the include_path (php.ini) or use set_include_path() - then the file will be looked up in all these locations.

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.

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.

I think it's important (at least for beginners) to mention somewhere clearly visible that require_once, when being used in a class, cannot be outside a function. (I am aware that even this, i.e. using it within the function is bad practice). However, that information could have saved me some valuable time troubleshooting the "unexpected T_REQUIRE_ONCE" error.

With both of your functions guys, Pure-PHP and jtaal at eljakim dot nl, you'll not have any variables available GLOBALly if they're supposed to be globals...

That's why my import handles better those situation. OK, SOME MAY DISPUTE that using include_once and require_once may slow down an application. But what's the use to do IN PHP what the interpreter *should* do better for you. Thusly these workarounds shall, some time in the future, DIE.

Thus It's better to well design your application to keep some order using few INCLUDES and REQUIRES in it rather than insert MANY AND SEVERAL *_once around.

I found it useful to have a function that can load a file relative to the calling script and return null if the file did not exist, without raising errors.

<?php/*Load file contents or return blank if it's not there.Relative to the file calling the function.*/echo relf(__FILE__, 'some.file');?>

It was easy to modify and just as useful for require/include.

<?php/*Require the file once.It's like suppressing error messages with @ but only when the file does not exist.Still shows compile errors/warning, unless you use @relro().Relative to the file calling the function.*/relro(__FILE__, 'stats.php');?>

If you work with a deep php file structure and a barrage of includes/requires/file-loads this works well.

Even though the documentation sais that "the path is normalized" that doesn't seem to be true in all cases.

If you are using the magic __autoload() function (or if the framework you're using is using it) and it includes the requested class file with complete path or if you override the include path in mid execution, you may have some very strange behavior. The most subtle problem is that the *_once functions seem to differentiate between c:\.... and C:\....

So to avoid any strange problems and painfull debugging make sure ALL paths you use within the system have the same case everywhere, and that they correspond with the actual case of the filesystem. That includes include paths set in webserver config/php.ini, auto load config, runtime include path settings or anywhere else.