David Hurst

PHP/MySQL, REALbasic, Javascript Developer

PHP - include all files in a folder

Ever wondered how to include every file, or a series of files in a folder without having to reference them individually? It’s easily done with PHP’s glob() function.

The glob() function finds pathnames that match a given pattern. This is highly useful in object oriented PHP, where you might have a folder called “classes” for instance, and you want all those files to be included. Here’s the code I use:

foreach(glob(”classes/*.php”) as $class_filename) {
     require_once($class_filename);
}

That’s it. Simple eh? You can use this method with include(), include_once(), require() and require_once(). Note the * wildcard being used in the glob() function - you can use this to get all files in a folder, or all files with a specific extension, or all files containing certain elements in the filename. It works just like the Linux or DOS command line wildcard.

I’ve seen some rather laborious ways of doing this. As with all things in PHP, there are a multitude of ways to achieve a specific goal, and who’s to say which are right or wrong. This method is certainly the quickest though.

RSS 2.0 | Trackback | Comment

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>