0

How can I check if a url directs to an image file, and http://website.com/images-stories/gallery/image-name.jpg

and if there is no file in the location, default to another url (for a default file).

I was using file_exists but realize that checks a path not a url.

<?PHP
    while ($data = mysqli_fetch_assoc($result)):

    $smaller_img = $data['smaller_img'];


    $url = $smaller_img;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
    curl_setopt($ch, CURLOPT_NOBODY, true);    // we don't need body
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT,10);
    $output = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

if ($httpcode=200) 
{
$smaller_imgf=$url;
} else {
$smaller_imgf='../images/submit_icon.png';
}  
    ?>

<img src="<?php echo $smaller_imgf; ?>
6
  • 2
    show us what you have tried so far Commented May 21, 2014 at 15:54
  • 1
    You should use cURL in addition to checking returning header Commented May 21, 2014 at 15:56
  • 3
    Looks a lot like: stackoverflow.com/questions/1722613/… Commented May 21, 2014 at 15:56
  • Agree with Stefan, but there's loads of dupes of this. Commented May 21, 2014 at 15:57
  • get_headers($url, 1) with stream_context set to only HEAD or - curl with fetch headers only Commented May 21, 2014 at 15:58

1 Answer 1

2

You can look with curl for status code 200

https://stackoverflow.com/a/11797723/2441442

If 200, you can check for image with getimagesize

http://www.php.net/manual/de/function.getimagesize.php

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @christian golhardt. I posted my current script and I'm having an issue, I have a feeling I'm doing something incorrectly when defining $httpcode
($httpcode=200) should be ($httpcode==200) ;)
@buzrw I recommend you a good IDE such as PHP Storm. It will warn you, if you make a mistake and have unreachable code :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.