Jump to content

[FILESYSTEM] Fetching every filename in a certain directory


flaab

Recommended Posts

Hello =)

 

I've a bunch of images en certain directories and I would like to display six of them in a random way.

 

So I need the make an 'ls' command on each one of them, and storing it's complete path into an Array position. And then, select some of the with the random function.

 

My problem is that I do not know how to make a dir / ls command in php and storing results.

 

How Can i do that?

 

Thanks in advance.

Link to comment
Share on other sites

Hi =)

 

Solved it with this. Returns the path to all files in a dir matching a regular expression.

 

<?php
function findfile($location='',$fileregex='') {
    if (!$location or !is_dir($location) or !$fileregex) {
       return false;
    }

    $matchedfiles = array();

    $all = opendir($location);
    while ($file = readdir($all)) {
    	/* Uncomment this block if you want subdir recursivity
       if (is_dir($location.'/'.$file) and $file <> ".." and $file <> ".") {
          $subdir_matches = findfile($location.'/'.$file,$fileregex);
          $matchedfiles = array_merge($matchedfiles,$subdir_matches);
          unset($file);
       }
      */
       if (!is_dir($location.'/'.$file)) {
          if (preg_match($fileregex,$file)) {
             array_push($matchedfiles,$location.'/'.$file);
          }
       }
    }
    closedir($all);
    unset($all);
    return $matchedfiles;
}
?>

 

Cheers.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

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

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