【问题标题】:How do I test if an remote image file exists in php?如何测试php中是否存在远程图像文件?
【发布时间】:2013-02-11 05:01:13
【问题描述】:

这会吐出一大堆“否”,但图像在那里并且路径正确,因为它们由 <img> 显示。

foreach ($imageNames as $imageName) 
{
    $image = 'http://path/' . $imageName . '.jpg';
    if (file_exists($image)) {
        echo  'YES';
    } else {
        echo 'NO';
    }
    echo '<img src="' . $image . '">';
}

【问题讨论】:

  • 图片文件的URL和服务器文件系统上同一个图片文件的路径是两个不同的字符串
  • 好吧,这是有道理的。使用带有 file_exists 的远程路径浏览其他帖子,我被误导了。

标签: php


【解决方案1】:

file_exists 使用本地路径,而不是 URL。

解决办法是这样的:

$url=getimagesize(your_url);

if(!is_array($url))
{
     // The image doesn't exist
}
else
{
     // The image exists
}

更多信息请参见information

此外,寻找响应标头(使用get_headers 函数)将是更好的选择。只需检查响应是否为 404:

if(@get_headers($your_url)[0] == 'HTTP/1.1 404 Not Found')
{
     // The image doesn't exist
}
else
{
     // The image exists
}

【讨论】:

  • 这很贵。在检索信息之前下载整个图像。您最好只查看请求的标头。查看 get_headers()。 php.net/manual/en/function.get-headers.php
  • @GeneKelly 谢谢!已更新。
  • 这是一个极好的答案(带有标题)。但它总是在不同的服务器上返回相同的标头吗?对不起,我对此一无所知。
  • 另外,您也可以使用 curl 并检查返回的 http 状态代码。如果是 404,则表示远处的图像不存在。
【解决方案2】:

file_exists 查找本地路径,而不是“http://” URL

使用:

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

【讨论】:

  • @Phil 你用 URL 试过了吗?它返回错误:codepad.viper-7.com/56dDzt
  • 如果服务器返回:HTTP/1.1 403 ?
  • 如果是403,图片仍然无法访问,但存在。
  • 是的,这行得通,但约翰的答案更简单,不会因 403 或标题中的拼写错误而失败。
  • 很好的解决方案。要检查文件是否可访问,您可以执行以下操作:$file_headers[0] != 'HTTP/1.1 200 OK'
【解决方案3】:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode==200) echo 'YES';
else              echo 'NO';

【讨论】:

    【解决方案4】:

    这就是我所做的。它通过获取标题涵盖了更多可能的结果,因为如果您无法访问该文件,它并不总是只是“404 Not Found”。有时它是“永久移动”、“禁止”和其他可能的消息。但是,如果文件存在并且可以访问,则只是“ 200 OK”。 HTTP 的部分后面可以有 1.1 或 1.0,这就是为什么我只是使用 strpos 来在每种情况下都更可靠。

    $file_headers = @get_headers( 'http://example.com/image.jpg' );
    
    $is_the_file_accessable = true;
    
    if( strpos( $file_headers[0], ' 200 OK' ) !== false ){
        $is_the_file_accessable = false;
    }
    
    if( $is_the_file_accessable ){
        // THE IMAGE CAN BE ACCESSED.
    }
    else
    {
        // THE IMAGE CANNOT BE ACCESSED.
    }
    

    【讨论】:

      【解决方案5】:
      function remote_file_exists($file){
      
      $url=getimagesize($file);
      
      if(is_array($url))
      {
      
       return true;
      
      }
      else {
      
       return false;
      
      }
      
      $file='http://www.site.com/pic.jpg';
      
      echo remote_file_exists($file);  // return true if found and if not found it will return false
      

      【讨论】:

        猜你喜欢
        • 2012-05-16
        • 2021-06-26
        • 2016-07-09
        • 2010-11-02
        • 1970-01-01
        • 2012-03-27
        • 2018-12-25
        • 2011-05-07
        相关资源
        最近更新 更多