Hello every one
«require_once» and «require» are language constructs and not functions. Therefore they should be written without «()» brackets!
require_once may not work correctly inside repetitive function when storing variable for example:
function foo () require_once( ‘var.php’ );
return $foo ;
>
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
function foo () require( ‘var.php’ );
return $foo ;
>
> php check2 . php
result :
bar
bar
bar
bar
bar
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):
$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 , 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», lstat64 («/www/includes», lstat64 («/www/includes/example.com», lstat64 («/www/includes/example.com/code», lstat64 («/www/includes/example.com/code/conf», .
lstat64 («/www/includes/example.com/code/conf/sql_servers.inc», 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
Php include all files in directory
Question: I’m trying to create a script for including (through require_once) multiple files, but I’m expecting from it following behavior: all file names of required files are defined as values in array script check if all files from array exist in given directory if yes, require them and continue (only if each of them exist) Then sort it by the change date And finally, do something with the sorted list Question: I wrote mini function for including all php files in directory How can I include all files in current directory excluding file itself (in which located function) ?
Show all files from directory beginning with newest file
I am trying to show all my files in a directory beginning with newest file added in directory. Right now I can only include all the files with the following code.
I also managed to include only the most recent file, but I cant seem to figure out how to do it all together. I would be happy for any help. Thanks
First fill an array with information — filename and change date
$files = array(); foreach( glob( "posts/*.php" ) as $filename ) < $files[] = array( "name" =>$filename, "change_date" => filectime( $filename ); ); >
Then sort it by the change date
usort( $files, function($a, $b) < return $a->change_date - $b->change_date; > );
And finally, do something with the sorted list
Include class files from another directory, php, I solved the issue. The mistake was I didn’t include the class inside the autoload file. So it doesn’t find the class.
How can I include all files in current directory excluding file itself
I wrote mini function for including all php files in directory
foreach (glob("*.php") as $filename)
How can I include all files in current directory excluding file itself (in which located function) ?
The following should help. You should just Get the current script file name and compare to the items from the array:
$this_file = basename($_SERVER['SCRIPT_FILENAME']); foreach (glob("*.php") as $filename) < if ($filename !== $this_file) < include $filename; >>
foreach (glob("*.php") as $filename)
foreach (array_diff(array_map('realpath',glob("*.php")), array(__FILE__) as $filename)
PHP to include all files from root directory (like a CMS)
I need to create subfolders with their own index.php files inside them for my pages. When I include the header and footer files in the root directory, however, the site breaks because the header file is looking for all the CSS and JavaScript files in the current directory.
You can use relative paths in the include, and .. to go up a directory.
This will include functions.php from the parent folder. If it were 2 folders deep, it would be ../../functions.php
This is the most common way of including things in other folders, actually providing a relative yet direct path. Using the parsers include_path can work but is not as portable.
Just a quick comparison of the execution plan of both approaches:
For the server side, add the root to your include_path setting (or, if you don’t intend to include from anywhere else, replace the include_path with the root), and you’ll be able to refer to the files in it from anywhere.
Client-side, you’d use the tag to tell a browser where URLs start from (ie: where relative URLs end up pointing to). You only really need this if you’re linking the CSS and JS rather than including them, but that’s the more common scenario. (You’d usually include PHP, and link CSS/JS.)
Include all files in a folder, php , I want to include all of folder2/ including the sub folder: folder3 as well as the php and json files inside folder2/ . I have looked at
PHP — include files from array only if all exist in directory
I’m trying to create a script for including (through require_once) multiple files, but I’m expecting from it following behavior:
- all file names of required files are defined as values in array
- script check if all files from array exist in given directory
- if yes, require them and continue (only if each of them exist)
- if no, terminate script and show error message (if any file is missing)
UPDATE
After taking a closer look at my original script I found why it didn’t work. Second IF statement ($countMissing == 0) was inside FOR loop and it produced empty arrays for files which were found. Taking that IF statement out of the loop sorted the problem.
WORKING VERSION (with few tiny modifications):
// Array with required file names $files = array('some_file', 'other_file', 'another_file'); // Count how many files is in the array $count = count($files); // Eampty array for catching missing files $missingFiles = array(); for ($i=0; $i < $count; $i++) < // If filename is in the array and file exist in directory. if (in_array($files[$i], $files) && file_exists(LIBRARIES . $files[$i] . '.php')) < // . update array value with full path to file $files[$i] = LIBRARIES . $files[$i] . '.php'; >else < // Add missing file(s) to array $missingFiles[] = LIBRARIES . $files[$i] . '.php'; >> // Count errors $countMissing = count($missingFiles); // If there was no missing files. if ($countMissing == 0) < foreach ($files as $file) < // . include all files require_once ($file); >> else < // . otherwise show error message with names of missing files echo "File(s): " . implode(", ", $missingFiles) . " wasn't found."; >
If this thread won’t be deleted I hope it will help somebody.
$files = array( 'some_file', 'other_file', 'another_file', ); // create full paths $files = array_map(function ($file) < return ROOT_DIR . $file . '.php') >, $files); // find missing files $missing = array_filter($files, function ($file) < return !file_exists($file); >); if (0 === count($missing)) < array_walk($files, function ($file) < require_once $file; >); > else < array_walk($missing, function ($file) < echo "File: " . $file " wasn't found."; >); >
- http://php.net/manual/en/function.array-map.php
- http://php.net/manual/en/function.array-filter.php
- http://php.net/manual/en/function.array-walk.php
Try this, prevent loop inside the loop.
The code from localheinz and jp might be fine, but I wouldn’t code things like that because it makes things complicated. Assuming you don’t want a list of missing files (which would be slightly different) I’d do it like this:
$filesOK=true; foreach($files as $file) < $path = ROOT_DIR . $file . ".php"; if(!file_exists($path )) < $filesOK=false; // we have a MIA break; // quit the loop, one failure is enough >> if($filesOK) foreach($files as $file) require_once($file); else echo "We have a problem";
For me this is much easier to see at a glance. Easier to debug, and the CPU is going to do the same job one way or anther. Probably not much difference in execution speed — if that even mattered.
If you need the list of missing files, then:
$filesOK=true; foreach($files as $file) < $path = ROOT_DIR . $file . ".php"; if(!file_exists($path)) // assume each file is given with proper path < $filesOK=false; // we have a MIA $mia[]=$path; // or $file if you just want the name >> if($filesOK) foreach($files as $file) require_once($file); else < if(is_array(@$mia)) // I always make sure foreach is protected foreach($mia as $badfile) // even if it seems obvious that its ok echo "Missing in action: $badfile
"; >
How to include() all PHP files from a directory ?, How to include() all PHP files from a directory ? ; Create file1.php in folder ‘myGeeks’: · echo «1st File Included Successfully
» ; ; Create