Tuesday, April 5, 2011

regex or something to find a file in php

I have a name in a database, lets say its "DFectuoso" and some legacy system stored DFectuoso_randomnameofafile.doc.

Now I want to find all the filed "DFectuoso" owns and display links to them in a PHP page.

What would be the way to start on this?

From stackoverflow
  • I'd try with glob() in combination with readfile().

    Off the top of my head:

    $findname = 'DFectuoso';
    foreach (glob('/path/to/somewhere/'.$findname.'*') as $file) {
      provide_a_link_to($file);
    }
    

    and just pass the file with readfile().

    Remember, if you are using $_GET to pass the chosen file to the user, sanitize and validate the permissions first. Don't do just readfile($_GET['chosenFile']); or you'll get in trouble!

    Mark Biek : My first thought was an exec() call to 'find'. Your way is much better.
  • A good way is using glob().

    $files = glob("PATH_TO_FILES/DFectuoso_*.doc");
    echo "<ul>\n";
    foreach($files as $f)
        echo '<li><a href="'.$f.'">'.$f."</a></li>\n";
    echo "</ul>\n";
    
  • In case it's not as simple as finding files with a certain prefix, you can do something like this:

    $files = glob('*');
    
    function filter_files($filename) {
        // Do any processing you want on the filename here
        $file_matches = preg_match('/^DFectuoso.*\.(doc|txt)$/', $filename);
        return $file_matches;
    }
    
    $found_files = array_filter($files, 'filter_files');
    

0 comments:

Post a Comment