简体   繁体   English

PHP Glob无限文件

[英]Php glob unlimited nr of files

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. 使用php,我需要将foto导入到我的页面,并且我需要从可能包含1000、2000或3000 foto的文件夹中导入它们。

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. 我将网站上每页的数量限制为50,但是我的php仍然需要1000或更多的数组,然后按日期对其进行排序。

I've tried the glob() function, but this won't work after the amount of files inside this page is too much. 我已经尝试过glob()函数,但是在此页面内的文件数量过多之后,此方法将无法工作。

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? 是否有更好的方法按日期对整个文件夹进行排序,然后采用有限的nr,例如文件50至100或文件200至250等?

$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. 现在,当我使用此文件夹中的1000多个文件(类似文件)执行此操作时,我的浏览器将崩溃,或者加载时间会非常长。 How can i improve this? 我该如何改善呢?

You could try to use readdir() instead of glob() like this: 您可以尝试使用readdir()代替glob()如下所示:

// 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. 注意上面的代码中没有错误处理,当然您应该检查以便成功打开目录,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM