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.

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?> 

 

Don't think it stores their complete path though.

 

This should help you:

 

http://au.php.net/manual/en/function.scandir.php

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.

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.