3

I would like to automatically include/require all .php files under all directories. For example:

(Directory structure)

-[ classes
    --[ loader (directory)
        ---[ plugin.class.php
    --[ main.class.php
    --[ database.class.php

I need a function that automatically loads all files that end in .php

I have tried all-sorts:

$scan = scandir('classes/');
foreach ($scan as $class) {
    if (strpos($class, '.class.php') !== false) {
        include($scan . $class);
    }
}
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Adam W
  • 317
  • 1
  • 3
  • 15

8 Answers8

7

Well, if you want to include all php files with a certain ending even in subdirectories, you have to make a recursive function. Something like this:

function load_classphp($directory) {
    if(is_dir($directory)) {
        $scan = scandir($directory);
        unset($scan[0], $scan[1]); //unset . and ..
        foreach($scan as $file) {
            if(is_dir($directory."/".$file)) {
                load_classphp($directory."/".$file);
            } else {
                if(strpos($file, '.class.php') !== false) {
                    include_once($directory."/".$file);
                }
            }
        }
    }
}

load_classphp('./classes');
Charlotte Dunois
  • 4,638
  • 2
  • 20
  • 39
  • 5
    OMG the `unset()`... If you don't want the `.` and `..`, don't ask for them. Learn what `scandir()` does, and its competition, like `glob()` – Rudie Aug 16 '14 at 12:20
  • I can see what it does. It's 6 loc. But it's still nasty and there are functions that do what you want. `glob()` without a pattern, to return all files and folders, except for `.` and `..`. And there are even more functions that do exactly what you want. – Rudie Aug 16 '14 at 12:56
  • Thankyou this code snippet did the job where several hours of tinkering around with glob and autoload did not. – lindsaymacvean Oct 01 '16 at 21:56
  • @lindsaymacvean glob would also work, again with a recursive function (like this https://stackoverflow.com/questions/39192691/browse-directory-recursively-and-get-files-name/39192868#39192868 - you can loop over the result then (but you could also modify the function to directly include the file)). – Charlotte Dunois Oct 01 '16 at 21:59
2

This is probably the simplest way to recursively find patterned files:

$dir = new RecursiveDirectoryIterator('classes/');
$iter = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($iter, '/^.+\.class\.php$/', RecursiveRegexIterator::GET_MATCH); // an Iterator, not an array

foreach ( $files as $file ) {
  include $file; // $file includes `classes/`
}

RecursiveDirectoryIterator is a tricky beast, so learning all about it is probably not doable. The interwebs has many specific examples though. The trick is to search for it.

Rudie
  • 52,220
  • 42
  • 131
  • 173
1

If the php files you want to include are PHP classes, then you should use PHP Autoloader

It's not a safe practice to include all php files in all directories automatically. Performance might be degraded if you're including unnecessary files.

Here's the code that should work (I have not tested it):

$scan = scandir('classes/');
foreach ($scan as $class) {
  if (strpos($class, '.class.php') !== false) {
    include('classes/' . $class);
  }
}

If you want recursive include RecursiveIteratorIterator will help you.

Community
  • 1
  • 1
ggirtsou
  • 2,050
  • 2
  • 20
  • 33
1
$dir = new RecursiveDirectoryIterator('change this to your custom root directory');
foreach (new RecursiveIteratorIterator($dir) as $file) {
    if (!is_dir($file)) {
        if( fnmatch('*.php', $file) ) // you can change the file extension to any that you require.
        /* do anything here */
    }
}
Mike Musni
  • 171
  • 1
  • 3
1
function autoload( $path ) {
    $items = glob( $path . DIRECTORY_SEPARATOR . "*" );

    foreach( $items as $item ) {
        $isPhp = pathinfo( $item )["extension"] === "php";

        if ( is_file( $item ) && $isPhp ) {
            require_once $item;
        } elseif ( is_dir( $item ) ) {
            autoload( $item );
        }
    }
}

autoload( dirname( __FILE__ ) . DIRECTORY_SEPARATOR . "classes" );
Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
0

An easy way : a simple function using RecursiveDirectoryIterator instead of glob().

function include_dir_r( $dir_path ) {
    $path = realpath( $dir_path );
    $objects = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path ), \RecursiveIteratorIterator::SELF_FIRST );
    foreach( $objects as $name => $object ) {
        if( $object->getFilename() !== "." && $object->getFilename() !== ".." ) {
            if( !is_dir( $name ) ){
                include_once $name;
            }
        }
    }
}
J.BizMai
  • 2,621
  • 3
  • 25
  • 49
0

One that I use is

function fileLoader($dir) {
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $path = $dir . '/' . $file;
        if (is_dir($path)) {
            __DIR__.$path;
        } else {
            require_once $path;
        }
    }
}

# calling the function
fileLoader('mydirectory')
Abdulbasit
  • 534
  • 8
  • 13
0

This case work for me.

private static function includeFolderRecursivly( $directory ) {
    $platforms = scandir( $directory );
    $platforms = array_diff( $platforms, array( '.', '..' ) );
    foreach ( $platforms as $item ) {
        if ( isset ( pathinfo( $item )['extension'] ) && pathinfo( $item )['extension'] == 'php') {
            require_once $directory . pathinfo( $item )['basename'];
        } else {
            self::includeFolderRecursivly( $directory . pathinfo( $item )['basename'].'/' );
        }
    }
}

Its including only files with extension '.php'