Require all files in a folder
Is there an easy way to programmatically require all files in a folder?
Probably only by doing something like this:
$files = glob($dir . '/*.php');
foreach ($files as $file) {
require($file);
}
It might be more efficient to use opendir()
and readdir()
than glob()
.
No short way of doing it, you'll need to implement it in PHP. Something like this should suffice:
foreach (scandir(dirname(__FILE__)) as $filename) {
$path = dirname(__FILE__) . '/' . $filename;
if (is_file($path)) {
require $path;
}
}
There is no easy way, as in Apache, where you can just Include /path/to/dir
, and all the files get included.
A possible way is to use the RecursiveDirectoryIterator from the SPL:
function includeDir($path) {
$dir = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($dir);
foreach ($iterator as $file) {
$fname = $file->getFilename();
if (preg_match('%\.php$%', $fname)) {
include($file->getPathname());
}
}
}
This will pull all the .php
ending files from $path
, no matter how deep they are in the structure.