Jump to content

Creating links to files in a directory recursively


sf_guy

Recommended Posts

I'm trying to create a PHP function that will go through an FTP directory and automatically create links to any files in that directory, and in any subdirectories. I've tried several attempts but keep getting "File not found" errors. The files have spaces in the names. I notice that the URL's have %20 in them instead, but this shouldn't be an issue, right?  Anyway, here's the code that doesn't work (I based this off some other code I found, it's not entirely original). The links show correctly and the mouseovers appear correct, but a "File Not Found" error is thrown when a user clicks on the link:

function getDirectory( $path = 'documents/user', $level = 0, $recurse = -1 ){

$ignore = array( 'cgi-bin', '.', '..','Thumbs.db' );
// Directories to ignore when listing output.

$dh = @opendir( $path );
// Open the directory to the handle $dh

while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory

    if( !in_array( $file, $ignore ) ){
    // Check that this file is not to be ignored

        $spaces = str_repeat( ' ', ( $level * 4 ) );
        // Just to add spacing to the list, to better
        // show the directory tree.

        if( is_dir( "$path/$file" ) ){
        // Its a directory, so we need to keep reading down...

            echo "<strong>$spaces $file</strong><br />";
            if ($recurse==-1) {
            // Recurse down through subdirectories                
            getDirectory( "documents/user/$file", ($level+1), $recurse );
            }
            
        } else {

            echo $spaces . "<a href='$path/$file'>$file</a><br />"; 
            // Print out the file name, and create a URL link to that file
        }

    }

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.