You can use the following function i just created:
function load_folder($folder, $ext = '.php') {
foreach (glob("$folder*$ext") as $file) {
if (file_exists($file)) {
require_once($file);
}
}
}
START EDIT
This is the new version of the same function. Now it allows you to specify folders as folder
or folder/
without crashing. Also now it loads all files in all folders and subfolders.
function load_folder($dir, $ext = '.php') {
if (substr($dir, -1) != '/') { $dir = "$dir/"; }
if($dh = opendir($dir)) {
$files = array();
$inner_files = array();
while($file = readdir($dh)) {
if($file != "." and $file != ".." and $file[0] != '.') {
if(is_dir($dir . $file)) {
$inner_files = load_folder($dir . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . $file);
}
}
}
closedir($dh);
foreach ($files as $file) {
if (is_file($file) and file_exists($file)) {
$lenght = strlen($ext);
if (substr($file, -$lenght) == $ext) { require_once($file); }
}
}
}
}
END EDIT
You can also specify a specific extension if you want to load for example only .txt
files in a folder you can execute is like this: load_folder('folder/', '.txt');
.
Remember that someone think that this is somehow insecure. Before using this function inside a business site, look for more opinion about the topic.
Notice also that if some of your files are regarding classes you could use the __autoload()
PHP native function to let PHP call the class where it is really needed (lazy loading).
References: