繁体   English   中英

PHP Glob无限文件

[英]Php glob unlimited nr of files

使用php,我需要将foto导入到我的页面,并且我需要从可能包含1000、2000或3000 foto的文件夹中导入它们。

我如何确保我的浏览器不会因为大量文件而立即崩溃? 我将网站上每页的数量限制为50,但是我的php仍然需要1000或更多的数组,然后按日期对其进行排序。

我已经尝试过glob()函数,但是在此页面内的文件数量过多之后,此方法将无法工作。

是否有更好的方法按日期对整个文件夹进行排序,然后采用有限的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" />';
  }
}

因此,这是我的代码示例。 现在,当我使用此文件夹中的1000多个文件(类似文件)执行此操作时,我的浏览器将崩溃,或者加载时间会非常长。 我该如何改善呢?

您可以尝试使用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;

注意上面的代码中没有错误处理,当然您应该检查以便成功打开目录,依此类推。

暂无
暂无

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

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