Check if image exists on remote server before uploading

I am trying to download images from a remote server, resize it and then save it to the local computer.

For this I use 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 he has a fatal flaw.

If for any reason one of these images is not available or does not exist. The Wideimage function causes a fatal error. Prevention of any other images that may exist during upload.

I tried to check a file 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 that will not work.

What am I doing wrong?

thanks

+4
source share
3 answers

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

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

You can 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 } 
0
source

After some digging on the net, I decided to request HTTP headers instead of a CURL request, since this seems to be less overhead.

This is an adaptation of Nick's comment on PHP forums: 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 feature a “quick and unpleasant solution”, although it works well for me :-)

0
source

All Articles