【问题标题】:Checking if thumbnail exists in PHP检查 PHP 中是否存在缩略图
【发布时间】:2012-03-12 19:54:30
【问题描述】:

我的目录结构是这样的。

 ...photo-album1/
 ...photo-album1/thumbnails/

假设我们在photo-album1/ 中有image1.jpg。此文件的缩略图是tn_image1.jpg

我想做的是检查photo-album1/ 中的每个文件是否在photo-album1/thumbnails/ 中有缩略图。如果他们刚刚继续,如果没有,则将文件名发送到另一个函数:generateThumb()

我该怎么做?

【问题讨论】:

  • glob() 获取目录列表,foreach() 循环,file_exists() 检查
  • @j08691 脚本很长,无法在此处发布
  • 我想说,只需链接缩略图,然后访问该网站并扫描您的网络服务器错误日志以查找 404 丢失缩略图。你试过吗?

标签: php image opendir


【解决方案1】:
<?php

$dir = "/path/to/photo-album1";

// Open directory, and proceed to read its contents
if (is_dir($dir)) {
  if ($dh = opendir($dir)) {
    // Walk through directory, $file by $file
    while (($file = readdir($dh)) !== false) {
      // Make sure we're dealing with jpegs
      if (preg_match('/\.jpg$/i', $file)) {
        // don't bother processing things that already have thumbnails
        if (!file_exists($dir . "thumbnails/tn_" . $file)) {
          // your code to build a thumbnail goes here
        }
      }
    }
    // clean up after ourselves
    closedir($dh);
  }
}

【讨论】:

    【解决方案2】:
    $dir = '/my_directory_location';
    $files = scandir($dir);//or use 
    $files =glob($dir);
    foreach($files as $ind_file){
    if (file_exists($ind_file)) {
        echo "The file $filexists exists";
        } else {
        echo "The file $filexists does not exist";
        }
    
    } 
    

    【讨论】:

    • 那是什么?哈哈。我知道 file_exists() 函数。问题是我不知道如何从父目录中一一获取文件并在缩略图目录中检查 thum
    • 使用 foreach 循环?并发布你的代码?没有它的 rofl 没有人能给出解决方案
    【解决方案3】:

    简单的方法是使用PHP的glob函数:

    $path = '../photo-album1/*.jpg';
    $files = glob($path);
    foreach ($files as $file) {
       if (file_exists($file)) {
          echo "File $file exists.";
       } else {
          echo "File $file does not exist.";
       }
    }
    

    感谢以上灵魂的基础知识。我只是向它添加 glob。

    编辑:正如 hakre 所指出的,glob 只返回现有文件,因此您可以通过检查文件名是否在数组中来加快速度。比如:

    if (in_array($file, $files)) echo "File exists.";
    

    【讨论】:

    • 嗯,glob 不只返回现有文件吗? ;)
    猜你喜欢
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2012-04-14
    • 1970-01-01
    • 2014-01-10
    相关资源
    最近更新 更多