How to include all PHP files in directory?
10,092
Solution 1
I always do that like this where you would put your include normally but then in a foreach:
foreach(glob('dir/*.php') as $file) {
include_once $file;
}
that is maybe not the best way, it is always a good idea to create a list maybe an array of filepaths and then put that in the foreach like:
$includes = array(
'path/to/file.php',
'path/to/another/file.php'
);
foreach($includes as $file) {
include_once $file;
}
then whenever you add a file you can add one to that list and it will be included
Solution 2
If the files are classes you can try:
function __autoload($class_name)
{
require_once 'dir/' . $class_name . '.php';
}
see Autoloading
Solution 3
The scandir()
function will return an array with all the files in a directory:
Author by
BestDeveloper
Developing means getting ahead in everything, not just writing code.
Updated on June 04, 2022Comments
-
BestDeveloper almost 2 years
I have a directory with php files, those files are auto-updating every day. Sometimes I add another (new) PHP file.
What is the best way to include all php files from the directory?
- List all files in directory?
- Create some config file with filenames? (need to update every time)
- List files in main php? (edit main file every time I add new php file to include)
- Other?
Thank you!