Question: 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);
    }
}

```

Answer: 
If the php files you want to include are PHP classes, then you should use [PHP Autoloader](http://php.net/manual/en/language.oop5.autoload.php)

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](https://stackoverflow.com/a/5893774/1294631).
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')

```