I think, therefore I am. I am, therefore I sail

PHP: Find a file within a given path

If you need to locate a file somewhere within a given path this code snipped will do it for you. Please note that it only works on files systems that can handle the Linux style architecture. This means that the code will likely not work on a Windows Server.

I created this snippet specifically to locate the WordPress wp-load.php file in the path, however it should be noted that I do not necessarily advocate this method, it simply worked and was quick to implement. I am posting it here for posterity. Perhaps someone can benefit from it.

Please post a comment if you know of a better solution.

Problem: wp-load.php is somewhere in the path but it is unknown where. wp-load.php needs to be included from a file that may potentially move around.

Solution:

/**
 * Searches for a file in the path upwards from the provided $path
 * 
 * NOTE: This *ONLY* works with Linux based path structures. I.E. Will likely
 * not work with any Windows server
 * 
 * @param String $file - Name of file to find
 * @param String $path - (Optional) Path to begin searching from. Defaults to current
 * @return Mixed - Full path to file or null if not found 
 */
function find_in_path( $file, $path = null ) {

    if( is_null( $path ) ) $path = getcwd();

    if( file_exists( "$path/$file" ) ) { 
        return "$path/$file";
    } else { 
        $path = explode( '/', $path );

        if( '' == $path['1'] ) 
            return null;

        unset( $path['0'] );
        unset( $path[ count( $path )] );

        return find_in_path( $file, '/' .implode( '/', $path ) );

    }
}

Usage:

require_once( find_in_path( 'wp-load.php' ) );

Previous

Amphibious buses arriving in Seattle

Next

MySQL: Show count of records in each table of a database

1 Comment

  1. What’s up, just wanted to say, I loved this post. It was inspiring. Keep on posting!

Powered by WordPress & Beards