56

Is there an easy way to programmatically require all files in a folder?

Martijn
  • 15,791
  • 4
  • 36
  • 68
never_had_a_name
  • 90,630
  • 105
  • 267
  • 383
  • 5
    this has been answered – josh123a123 Feb 27 '14 at 17:55
  • 1
    @salathe For the sake of answering this question. I just stumbled over the same problem. My reason for example is that I have a lot of ObjectTypes defined in their corrosponding php file. I have one single php file connecting all the others and I need all my ObjectTypes to be included for my program to work. Also, my program is extending. For each new ObjectType I would again have to put a new line to require it. This way I make sure that all ObjectTypes are always required. – Daidon Nov 15 '17 at 02:44

10 Answers10

57

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

Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
  • 8
    @BorisŠuška: the question was "how to require all files in a folder". there was no requirement for recursion or to handle the case that the php file containing the code would be in the same folder. – Tom Haigh Nov 27 '13 at 10:55
  • @BorisŠuška: that snippet only includes itself if $dir is set to the same folder as __DIR__. That's not a bug, the snippet doesn't address what you set your variables to. – moopet Jul 25 '14 at 09:47
26

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;
    }
}
soulmerge
  • 73,842
  • 19
  • 118
  • 155
  • 2
    Wouldn't that particular snippet include itself over an over in an infinite loop? Plus, you can use `__DIR__` instead of `dirname(__FILE__)`. But I get the general idea. – Camilo Martin Nov 20 '13 at 18:25
  • 1
    -1 because snippet includes itself and it is not working recursively – Boris Šuška Nov 26 '13 at 22:07
  • 1
    The idea here is fine, but 1) it can be done a little more succinctly, Tom Haigh's answer shows, and 2) I know it's just an example, but the fact that implementation here is hard-coded to include files from the directory of the currently running script is kind of odd, especially since the currently running script itself isn't excluded. If you stick this in an empty folder and run it it will include itself forever until it segfaults. – Mark Amery Aug 13 '14 at 22:32
15

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.

Rando Hinn
  • 1,255
  • 19
  • 41
K. Norbert
  • 10,494
  • 5
  • 49
  • 48
  • 1
    Should be if (preg_match('%\.php$%', $fname)) { include($file->getPathname()); } – Simon Bennett Nov 22 '13 at 13:05
  • I really like this solution, it allowed me to have a folder `/classes/` that I autoload with composer, and a folder `/functions/` that are also grouped by namespaces, but since composer can't autoload functions nor include files from a folder with wildcards (all files need to be listed in composer.json one by one) - I ended up using this function. – dev_masta Jun 02 '20 at 00:33
13

Simple:

foreach(glob("path/to/my/dir/*.php") as $file){
    require $file;
}
Tanner Ottinger
  • 2,970
  • 4
  • 22
  • 28
5

Use a foreach Loop.

foreach (glob("classes/*") as $filename) {
  require $filename;
}

For more details, check out this previously posted question:

Community
  • 1
  • 1
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
  • Is this a bad way to require files ? Could this create a performance problems ? – RPDeshaies Jun 13 '14 at 14:49
  • @Tareck117 How so? What would be a faster method? – Joshua Pinter Jun 13 '14 at 17:16
  • 1
    I didn't meant that YOUR method was slow, I meant : Is it bad to include file in a `foreach(glob("folder"))` VS including them one after another ? – RPDeshaies Jun 13 '14 at 18:39
  • 1
    @Tareck117 No worries, Tareck, you might be right. :) Just figuring out what could be changed. On the face of it, I don't think there's a big performance hit with a `foreach` loop. The only issue I could see arising is if the number of files is extremely large. I'd love to hear others thoughts on this, too. – Joshua Pinter Jun 13 '14 at 19:41
  • I would also be interested to hear if a Recursive loop could also be a slow process ! – RPDeshaies Jun 13 '14 at 20:20
2

Solution using opendir, readdir, closedir. This also includes subdirectories.

<?php
function _require_all($path, $depth=0) {
    $dirhandle = @opendir($path);
    if ($dirhandle === false) return;
    while (($file = readdir($dirhandle)) !== false) {
        if ($file !== '.' && $file !== '..') {
            $fullfile = $path . '/' . $file;
            if (is_dir($fullfile)) {
                _require_all($fullfile, $depth+1);
            } else if (strlen($fullfile)>4 && substr($fullfile,-4) == '.php') {
                require $fullfile;
            }
        }
    }

    closedir($dirhandle);
}        

//Call like
_require_all(__DIR__ . '/../vendor/vlucas/phpdotenv/src');
Mirco Babin
  • 171
  • 1
  • 3
1

As require_all() function:

//require all php files from a folder
function require_all ($path) {

    foreach (glob($path.'*.php') as $filename) require_once $filename;

}
Victor
  • 581
  • 6
  • 15
  • This is a duplicate of three previous answers. All it changes is require to require_once, and that's not part of the question. – moopet Jul 25 '14 at 09:50
0

recursively all file list and require_once in one directory:

$files = array();

function require_once_dir($dir){

       global $files;

       $item = glob($dir);

       foreach ($item as $filename) {

             if(is_dir($filename)) {

                  require_once_dir($filename.'/'. "*");

             }elseif(is_file($filename)){

                  $files[] = $filename;
             }
        }
}

$recursive_path = "path/to/dir";

require_once_dir($recursive_path. "/*");

for($f = 0; $f < count($files); $f++){

     $file = $files[$f];

     require_once($file);
}
Raju Ram
  • 943
  • 9
  • 15
0

My way to require all siblings:

<?php
$files = glob(__DIR__ . '/*.php');
foreach ($files as $file) {
    // prevents including file itself
    if ($file != __FILE__) {
        require($file);
    }
}
userlond
  • 3,632
  • 2
  • 36
  • 53
0

I came across this question and modified a bit the accepted answer. My strategy is drop this file in the folder then require it elsewhere.

<?php

// The generic "load everything in this folder except myself"

foreach (scandir(__DIR__) as $filename) {
    if (!in_array($filename, [basename(__FILE__), ".", ".."])) {
        $path = __DIR__ . DIRECTORY_SEPARATOR . $filename;
        if (is_file($path)) {
            require_once $path;
        }
    }
}

It is very useful if you have folders like Controllers or Models. It allows you to create new files with no need to worry about require.

Bruno Polo
  • 657
  • 5
  • 11