【问题标题】:Find if a file exists, if not, revert to original path查找文件是否存在,如果不存在,恢复到原始路径
【发布时间】:2011-06-21 14:46:47
【问题描述】:

我编写了一个函数来获取图像路径,在其末尾添加一些文本,然后将其重新组合在一起。在将新文本附加到图像后,我正在尝试编写一个 if else 分支来测试文件是否存在。

比如我请求图片路径:

http://example.com/image1.jpg

可以改成这样:

http://example.com/image1-150x100.jpg

该函数是为 WordPress 设计的,因此需要 $post->ID 参数、自定义字段名称、预期目标的宽度和高度。

函数如下:

function get_galleria_image ( $post_id, $customFieldName, $width, $height ) {

    $imagePath = get_post_meta($post_id, $customFieldName, true);

    $splitImage = explode('.', $imagePath);

    $count = count($splitImage);

    $firstHalf =  array_slice($splitImage, 0, $count-1);

    $secondHalf = array_slice($splitImage, $count-1);

    $secondHalf[0] = '-' . $width . 'x' . $height . '.' . $secondHalf[0];

    $firstHalfJoined = implode('.', $firstHalf);

    $completedString = $firstHalfJoined . $secondHalf[0];

    // if the filename with the joined string does not exist, return the original image
    if (file_exists($completedString)){
        return $completedString;
    } else {
        return $imagePath;
    }
}

我知道这很粗糙,因此欢迎任何压缩此代码并使其“更好”的想法。我发现该函数始终返回原始图像路径。 file_exists() 可以采用像“http://example.com/image1.jpg”这样的绝对路径,还是只接受根风格的绝对路径,如“/path/to/file/image1.jpg”?

【问题讨论】:

    标签: php wordpress file-exists


    【解决方案1】:

    file_exists 不接受 url 路径。试试这个 url 路径来检查给定的 url 是否是图像

    function isImage($url)
      {
         $params = array('http' => array(
                      'method' => 'HEAD'
                   ));
         $ctx = stream_context_create($params);
         $fp = @fopen($url, 'rb', false, $ctx);
         if (!$fp) 
            return false;  // Problem with url
    
        $meta = stream_get_meta_data($fp);
        if ($meta === false)
        {
            fclose($fp);
            return false;  // Problem reading data from url
        }
    
        $wrapper_data = $meta["wrapper_data"];
        if(is_array($wrapper_data)){
          foreach(array_keys($wrapper_data) as $hh){
              if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19 
              {
                fclose($fp);
                return true;
              }
          }
        }
    
        fclose($fp);
        return false;
      }
    

    【讨论】:

      【解决方案2】:

      据我所知,file_exists() 只检查本地文件系统上的文件或目录是否存在。您可能希望通过fsockopen() 连接到另一台服务器,然后检查 HTTP 代码以了解该文件是否存在。

      // you will need to set $host and $file
      
      $sock = fsockopen ( $host );
      fwrite ( $sock, "HEAD ".$image." HTTP/1.1\r\n" );
      fwrite ( $sock, "Host: ".$file."\r\n" );
      fwrite ( $sock, "Connection: close\r\n\r\n" );
      
      // Get the first twelve characters of the response - enough to check the response code
      if ( fgets ( $sock, 12 ) == "HTTP/1.1 404" )
          //file doesn't exist
      else
          //file exists
      
      fclose ( $sock );
      

      【讨论】:

      • HTTP HEAD 请求(ayush 使用)比使用 GET 更好,HEAD 请求只返回标头,服务器不会尝试自己发送图像。
      • 该死,我什至不知道这些基本的 HTTP 东西。我真的应该读一遍 RFC。感谢您的关注。
      • 有趣的是,至少有 2 人认为 @ayush 有一个很好的答案,但没有人费心去投票;唯一的赞成票是我的 ;-)
      • 如果可以的话,我会的。刚加入这个不错的社区,还没有足够的声望投票。
      • @andre_roesti 好点,让我帮你。如果您连接多个堆栈交换帐户,我认为您还可以立即获得 100 代表奖励。
      【解决方案3】:

      要使程序的第一部分更紧凑,您可以执行以下操作:

      $completedString = preg_replace("/(.+)\.([^.]+)$/siU", "$1" . "-" . $width ."x" . $height . "$2", $splitImage);
      

      然后使用@ayush发布的函数来检查远程服务器上的文件

      【讨论】:

        【解决方案4】:
        if(@getimagesize($imghttppath))
        {
             echo '<img src="'. $imghttppath . '" />';
        }
        else
        {
             echo '<img src="http://www.domain.com/images/default.jpg" />';
        }
        

        getimagesize 的用法有点不正统,除非你关闭错误,否则它必须是@,因为如果文件不存在它会返回错误。但它就像你能得到的一样简单。使用外部 URL、本地 URL、本地绝对路径和工作目录的相对路径来检查图像是否存在并且是实际图像。

        【讨论】:

          猜你喜欢
          • 2018-03-27
          • 1970-01-01
          • 2016-09-05
          • 1970-01-01
          • 2014-11-27
          • 1970-01-01
          • 1970-01-01
          • 2011-12-14
          • 2019-08-08
          相关资源
          最近更新 更多