Autoloading files in directory with PHP
// $dir = path/to/directory/
function load_files( $dir ) {
// Declare the results array to return.
$results = array();
// Scan the dir for files.
$files = scandir( $dir );
// Loop through the files in the directory.
foreach ( $files as $file ) {
// Exclude . and ..
if ( ('.' === $file ) || ( '..' === $file ) ) {
continue;
}
// Get the path to the file.
$file = $dir . '/' . $file;
// Get the file header info.
$header = get_file_data( $file, array( 'Load' => 'Load' ) );
// Get the file extension.
$extension = substr( $file, strrpos( $file, '.' ) + 1 );
// If 'Load' is true and the file is a PHP file.
if ( 'true' === $header['Load'] && 'php' === $extension ) {
$results[] = $file;
}
}
// Return the results array.
return $results;
}
/**
* Load: true
*/
// Do some stuff.
// Get the file to include.
$files = load_files( 'path/to/directory/' );
// Loop through the files array.
foreach ( $files as $file ) {
// Verify that the file exists.
if ( file_exists( $file ) ) {
// Include the file.
include $file;
}
}