Jump to content

Creating links to files in a directory recursively


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


Link to comment
Share on other sites

Thanks. That fixed it and also some of the links had hash tags in the file names, which is a no-no, so I told the client to stop posting files with names like "Production Issue #1.doc" and use "Production Issue No 1.doc" instead.

Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • 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.