1

I am displaying large number of remote images in my PHP webpage and I need to check if the image exists in-order-to handle no image condition. But this process takes heavy load to check the condition for each remote file. Please anyone suggest your views to handle this.

Thanks in advance.

Ashok
  • 11
  • 2
  • 1
    use file_exists() function; – Saty Apr 23 '15 at 06:55
  • @saty : Thanks for reply. My problem is I cannot use these functions @GetImageSize(), and file_exists() for each image. It increases load on page. – Ashok Apr 23 '15 at 07:02

3 Answers3

2

I think there are several solutions

  1. If you display remote images (those images which are not located at your server) on your webpage, you can check if image exists by javascript. I mean create the image and check if it was loaded. Then handle the exception by javascript.
  2. You can check image existence before displaying them to users. For example while adding them to your website. So you do it just once, store results in your database, and then display only those images which you know exist.
  3. There is a PHP function curl_multi_exec. It allows you to perform several http requests simultaneously.

You better copy those images to your server. If you do, you will be sure the images still exist and are not modified.

phoenix.mstu
  • 164
  • 9
  • I would prefer javascript solution. By using javascript, the user can quickly receive the webpage and feel more responsive. If you still want to use server side checking, make sure you use some kind of cache... – amit bakle Apr 23 '15 at 07:19
0

Instead of getting the whole file, just check if requesting a remote image returns HTTP status code 200 (found) or something else (e.g. 404 not found).

Try this answer: How can one check to see if a remote file exists using PHP?

You can instruct curl to use the HTTP HEAD method via CURLOPT_NOBODY.

More or less

   $ch = curl_init("http://www.example.com/favicon.ico");
   
   curl_setopt($ch, CURLOPT_NOBODY, true);
   curl_exec($ch);
   $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
   // $retcode >= 400 -> not found, $retcode = 200, found.
   curl_close($ch);
Community
  • 1
  • 1
Tim
  • 43
  • 5
0

Something like this might work.

<script type="text/javascript">
  //Example error handling
  var imgPlaceHolder = '//example.com/no-img.jpg';
  var handelImageNotFound = function (imgId) {
    $('#' + imgId).attr("src", imgPlaceHolder);
  }
</script>

<?php
$imgList = [
    '//example.com/foo1.jpg',
    '//example.com/foo2.jpg',
    '//example.com/baz.jpg',
];
?>

<?php for ($index = 0; $index < count($imgList); $index++): ?>
  <img src="<?= $imgList[$index] ?>" id="img_<?= $index ?>" onerror="handelImageNotFound('img_<?= $index ?>')" />
<?php endfor; ?>

Now you will have to write a javascript method "handelImageNotFound(imgId)" function to handle missing images.

amit bakle
  • 3,321
  • 1
  • 15
  • 14