Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if an remote image file exists in php?

Tags:

php

This spits out a whole heap of NO's but the images are there and path correct as they are displayed by <img>.

foreach ($imageNames as $imageName) 
{
    $image = 'http://path/' . $imageName . '.jpg';
    if (file_exists($image)) {
        echo  'YES';
    } else {
        echo 'NO';
    }
    echo '<img src="' . $image . '">';
}
like image 874
TijuanaKez Avatar asked Feb 11 '13 05:02

TijuanaKez


2 Answers

file_exists uses local path, not a URL.

A solution would be this:

$url=getimagesize(your_url);

if(!is_array($url))
{
     // The image doesn't exist
}
else
{
     // The image exists
}

See this for more information.

Also, looking for the response headers (using the get_headers function) would be a better alternative. Just check if the response is 404:

if(@get_headers($your_url)[0] == 'HTTP/1.1 404 Not Found')
{
     // The image doesn't exist
}
else
{
     // The image exists
}
like image 118
Ionică Bizău Avatar answered Oct 06 '22 01:10

Ionică Bizău


file_exists looks for a local path, not an "http://" URL

use:

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}
like image 22
Chris Christensen Avatar answered Oct 06 '22 01:10

Chris Christensen