2011-05-06 93 views
4

我试图从远程服务器下载图像,调整大小,然后保存本地机器。下载前检查图像是否存在于远程服务器

要做到这一点我使用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)); 

但是,这是行不通的。

我在做什么错?

感谢

+0

为什么'file_exists()'检查工作,'$ row_getImages'如何定义? – 2011-05-06 14:56:30

+0

$ row_getImages在包含的query.php中定义。 file_exists()似乎不起作用。 – jamjam 2011-05-06 15:00:39

+0

不知道发生了什么回答,提到“尝试”和“赶上”,但它的工作。感谢大家。 – jamjam 2011-05-06 15:11:11

回答

4

this page,file_exists无法检查远程文件。有人建议在那里,在评论中,他们使用的fopen作为一种解决方法:

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

你可以通过卷曲检查:

$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 
} 
+0

不工作。总是“$ httpcode”小于400,文件存在或不存在。非常糟糕的帖子。 – 2014-03-20 08:15:15

0

经过一番周围的净我决定请求的HTTP头挖,而不是CURL请求,显然它的开销较小。

这是从PHP论坛在尼克的评论的适应: 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" />'; 
} 

尼克调用这个函数“快速和肮脏的解决方案”,但它是为我工作很好:-)

相关问题