4

Im trying to download images from remote server, resize and then save it local machine.

To do this I use a 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)); 


?>

This works most of the time. But it has a fatal flaw.

If for some reason one of these images is not available or doesn't exists. Wideimage throws a fatal error. Preventing any further images that may exist from downloading.

I have tried checking file exists like this

    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)); 

But this doesn't work.

What am I doing wrong??

Thanks

jamjam
  • 51
  • 1
  • 3

3 Answers3

5

According to this page, file_exists cannot check for remote files. Someone suggested there, in the comments, that they use fopen as a workaround:

<?php
function fileExists($path){
    return (@fopen($path,"r")==true);
}
?>
Dave
  • 28,833
  • 23
  • 113
  • 183
0

After some digging around the net I decided on requesting the HTTP headers, instead of a CURL request, as apparently it's less overhead.

This is an adaption of Nick's comment from the PHP forums at: 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 calls this function "a quick and nasty solution", although it is working well for me :-)

AdheneManx
  • 306
  • 3
  • 11
0

You could check via 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
}
scurker
  • 4,733
  • 1
  • 26
  • 25