Php glob unlimited nr of files

422 views Asked by At

with php i need to import foto's to my page, and i need to import them from a folder that may contain more than 1000, 2000 or 3000 foto's.

How can i make sure that my browser won't crash instantly because the huge amount of files? I limited the amount per page on my site to 50, but still my php takes a 1000 or more to it's array and then sorts it by date.

I've tried the glob() function, but this won't work after the amount of files inside this page is too much.

Is there a better way to sort the whole folder by date and then take a limited nr such as files 50 to 100 or files 200 to 250 etc?

$files1 = glob('../fotos/*.JPG');
$files2 = glob('../fotos/*.jpg');
$files = array_merge($files1, $files2);
usort($files, function($b,$a){
    return filemtime($a) - filemtime($b);
});

$filesPerPage = 50;
$page = $_GET['page']; //FOR INSTANCE: 1 OR 2 OR 5 ETC..
$filesMIN = ($page - 1) * $filesPerPage;
$filesMAX = $page * $filesPerPage;
$fileCount = 0;
foreach($files as $file) {
  $fileCount++;
  if($fileCount > $filesMIN && $fileCount <= $filesMAX) {
    echo '<img src="$file" />';
  }
}

So, this is a sample of my code. Now when i do this with more than a 1000 files (something like that) in this folder, my browser will crash, or the loading time will be really long. How can i improve this?

1

There are 1 answers

4
Cyclonecode On BEST ANSWER

You could try to use readdir() instead of glob() like this:

// loop through the directory and add all *.jpg && *.JPG files to an array
$filesPerPage = 50;
$page = intval($_GET['page']);
$filesMIN = ($page - 1) * $filesPerPage;
$filesMAX = $page * $filesPerPage;
// set the counter to the offset value
$fileCount = $filesMIN;
$files = array();
$dir = opendir("../photos");
while(false !== ($file = readdir($dir))) {
  $ext = pathinfo($file, PATHINFO_EXTENSION);
  if(($ext == 'jpg' || $ext == 'JPG') && $fileCount >= $filesMIN && $fileCount < $filesMAX) {
     $fileCount++;
     $files[] = $file;
  }
}
closedir($dir);

// now sort the array
usort($files, function($b,$a){
   return filemtime($a) - filemtime($b);
});

// and finally output each image
$output = '';
foreach($files as $file) {
  $output .= '<img src="'.$file.'" />';
}
print $output;

Notice that there are no error handling in the above code, of course you should check so the directory is opened successfully and so on.