views:

33

answers:

2

Hi, a little question. I have this code, which is works perfect for files, but If am trying search on a directory name, the result is blank. How I can fix that?

<?php
function listdirs($dir,$search)
{
    static $alldirs = array();
    $dirs = glob($dir."*");
    foreach ($dirs as $d){
        if(is_file($d)){
            $filename = pathinfo($d);
            if(eregi($search,$filename['filename'])){   
                print  "<a href=http://someurl.com/" . $d .">". $d . "</a><br/>";
            }
        }else{
            listdirs($d."/",$search);
        }
    }
}
$path = "somedir/";
$search= "test";
listdirs($path,$search);
?>

somedir/test/

result: blank (I want: /somedir/test/)

somedir/test/test.txt

result: OK

I want to search also in the directory names, how I can do that?

A: 

Your script is working fine. I think the webserver user does not have permissions to the given directory.

Sjoerd
In that case how is possible this?Searching for "two"one/two/ (directory structure)result: blank (I want: /one/two/)Searching for file "test" or "test.txt" is working fine.one/two/test.txtresult: OK (result: one/two/test.txt)File search is working ok, but any of the directory search not. I think it is not a premission problem.
Peter
A: 

If you want to search for a directory, you're going to have to change the if(is_file($d)) block. Right now, you're having it simply call listdirs again when it encounters a directory... but this also means you'll never see a print with a link to said directory.

I suggest doing something like this in the foreach instead:

    $filename = basename($d);
    if(eregi($search,$filename)){   
        print  "<a href=http://someurl.com/" . $d .">". $d . "</a><br/>";
    }
    if(is_dir($d)){
        listdirs($d."/",$search);
    }
R. Bemrose
Thank you very very much! You helped me a lot!
Peter
Another litte question, is this code safe? Users can't list the server files? Only what I get from users is the $search variable.
Peter
@Peter: It *should* be safe, because of the `basename` call. However, I've never tried it before, so I can't say for certain that they can't break out of it using specially encoded characters.
R. Bemrose