Something that can become annoying when working on a php project is all of the includes you have to do. More to the point is all of the path changes you have to do. Depending on how the project was built it could be an easy task such as ‘include(”../file.php”)’. However in the real world sometimes your working on a project that you’ve inherited and the folder structure can be much messier than that. A handy tool in some circumstances is a recursive function that requires the name of the file and the function finds the file recursively through your folder structure:
static function include_file($name, $include_type = 'include', $relative_uri = "..") { $ignore_files = array( 'cgi-bin', '.', '..' ); $dir = opendir($relative_uri); while(false !== ($file = readdir($dir))) { if (! in_array($file, $ignore_files)) { if(is_dir("$relative_uri/$file")) { self::include_file($name, "$relative_uri/$file"); } elseif (!is_dir("$relative_uri/$file")) { if ($file == $name) { if ($include_type == 'include') { include("$relative_uri/$file"); } else if ($include_type == 'include_once') { include_once("$relative_uri/$file"); } else if ($include_type == 'require') { require("$relative_uri/$file"); } else if ($include_type == 'require_once') { require_once("$relative_uri/$file"); } closedir($dir); return true; } } } } @closedir( $dir ); return false; }
Here’s an example of how to use the function:
// Basic usage include_file('test.php'); // Require instead of include include_file('test.php', 'require'); //Recursive search in a particular folder include_file('test.php', 'include', 'app_lib');
Something to note in the $relative_uri parameter we have a default string of ‘..’. This could be the path to the root of the project such as ‘c:\…’ or ‘/etc/…’ (depending on what operating system you are using). That will force the default of that parameter to recursively search your entire application structure.
Use this function with care as it does cost some overhead scanning for files. However I’ve found this to work perfectly for smaller applications that don’t have millions of users connecting to it.
Tags: PHP
Related Links
Leave a Reply
You must be logged in to post a comment.
