Require all the files in a directory

Views: 6 Last modified: September 17th, 2011 Comments: 0

The below function will require all the files in a specific directory. If you call the function “requirefiles” (the below snippet), including 2 parameters, from some file in some directory, it will require all those files in that specific directory.

For example, you define the below function in the file “functions.php” and finally you call this function (including two parameters) in the file “header.php”, in the directory “front”, it will require (require_once) all the files in the directory “front”. It skips parent & child directory’s.

The first parameter require the pattern of the desired files, and the second parameter needs the file extension.
You can find some examples on the bottom.

Wild characters = *

<?php
/**
 * requirefiles()
 * Require once all files in the directory
 * @param mixed $file_pattern
 * @param mixed $file_ex
 * @return
 */
function requirefiles($file_pattern = null, $file_ex = null){
    // Do backtrace
    $backtrace = @debug_backtrace();

    // If needed stop the script entirely
    if (is_null($file_ex) || is_null($file_pattern))
        exit('Parameter forgotten for a call on function <strong>'.__FUNCTION__.'</strong> at file
                   <strong>'.$backtrace[0]['file'].'</strong> at line <strong>'.$backtrace[0]['line'].'</strong>');

        // require once all the files
        foreach (glob((string)$file_pattern.(string)$file_ex) as $file){
            if ($file == basename($backtrace[0]['file']) || is_dir($file)){
                continue;
            }
                require_once $file;
        }

        // Stop function
        return;
}
?>

Some examples.

<?php
/**
*       * matches every character
*/

// require all files which matches the file name pattern "cripts", with all extensions
requirefiles('*cripts*','*');

// require the file script.php
requirefiles('script','.php');

// require all files with all extensions
requirefiles('*','*');

// require all files which matches the file name pattern "script", with the extension ".php"
requirefiles('script*','.php');
?>
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)
    Bluehost

    Mail this!

    To: From:Sum {5+6} =  
    Anything to add ?

        You must be logged in to post a comment.