【问题标题】:Check if image exists on remote server before downloading下载前检查远程服务器上是否存在图像
【发布时间】:2011-08-20 06:24:33
【问题描述】:

我正在尝试从远程服务器下载图像,调整大小,然后将其保存到本地计算机。

为此,我使用 WideImage。

<?php 

include_once($_SERVER['DOCUMENT_ROOT'].'libraries/wideimage/index.php');

include_once($_SERVER['DOCUMENT_ROOT'].'query.php');    


do { 


wideImage::load($row_getImages['remote'])->resize(360, 206, 'outside')->saveToFile($_SERVER['DOCUMENT_ROOT'].$row_getImages['local']);}

while ($row_getImages = mysql_fetch_assoc($getImages)); 


?>

这在大多数情况下都有效。但它有一个致命的缺陷。

如果由于某种原因这些图像之一不可用或不存在。 Wideimage 引发致命错误。阻止下载任何可能存在的其他图像。

我尝试过像这样检查文件是否存在

    do { 

if(file_exists($row_getImages['remote'])){

    wideImage::load($row_getImages['remote'])->resize(360, 206, 'outside')->saveToFile($_SERVER['DOCUMENT_ROOT'].$row_getImages['local']);}

}        
    while ($row_getImages = mysql_fetch_assoc($getImages)); 

但这不起作用。

我做错了什么??

谢谢

【问题讨论】:

  • 为什么file_exists() 检查有效,$row_getImages 是如何定义的?
  • $row_getImages 在包含的 query.php 中定义。 file_exists() 似乎根本不起作用。
  • 不确定如何回答提到的“尝试”和“捕捉”,但它确实有效。谢谢大家。
  • 您能否将您的 try and catch 解决方案添加到您的帖子中,以便其他人也可以从中受益?

标签: php file-get-contents file-exists


【解决方案1】:

根据this page,file_exists 无法检查远程文件。有人在 cmets 中建议他们使用 fopen 作为解决方法:

<?php
function fileExists($path){
    return (@fopen($path,"r")==true);
}
?>

【讨论】:

    【解决方案2】:

    您可以通过 CURL 检查:

    $curl = curl_init('http://example.com/my_image.jpg');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_NOBODY, TRUE);
    $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    if($httpcode < 400) {
      // do stuff
    }
    

    【讨论】:

    • 不工作。总是 "$httpcode" 小于 400,文件存在与否不存在。非常糟糕的帖子。
    【解决方案3】:

    在网上搜索了一番后,我决定请求 HTTP 标头,而不是 CURL 请求,因为显然它的开销更少。

    这是对来自 PHP 论坛的 Nick 评论的改编: http://php.net/manual/en/function.get-headers.php

    function get_http_response_code($theURL) {
       $headers = get_headers($theURL);
       return substr($headers[0], 9, 3);
    }
    $URL = htmlspecialchars($postURL);
    $statusCode = intval(get_http_response_code($URL));
    
    if($statusCode == 200) { // 200 = ok
        echo '<img src="'.htmlspecialchars($URL).'" alt="Image: '.htmlspecialchars($URL).'" />';
    } else {
        echo '<img src="/Img/noPhoto.jpg" alt="This remote image link is broken" />';
    }
    

    Nick 称这个函数为“一个快速而讨厌的解决方案”,尽管它对我来说效果很好:-)

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 2013-04-30
      • 2010-11-24
      • 2012-06-13
      • 2014-06-27
      • 2012-05-16
      • 2021-01-07
      • 1970-01-01
      • 2015-07-11
      相关资源
      最近更新 更多