0

Suppose I've one URL which is supposed to represent an image i.e. if I enter the same URL in an address bar and hit it, the image should display in a browser window.

If the URL doesn't have any image present at it it should return false otherwise it should return true.

How should this be done in an efficient and reliable way using PHP ?

perror
  • 7,071
  • 16
  • 58
  • 85
PHPLover
  • 1
  • 51
  • 158
  • 311

3 Answers3

1

I use this little guy:

function remoteFileExists($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if (curl_exec($ch)) return true;
    else return false;
}

Use like:

if (remoteFileExists('https://www.google.com/images/srpr/logo11w.png')){
    echo 'Yay! Photo is there.';
} else {
    echo 'Photo no home.';
}
Madness
  • 2,730
  • 3
  • 20
  • 29
  • This post pretty much confirms this is the right way to go: http://stackoverflow.com/questions/1363925/check-whether-image-exists-on-remote-url – Madness Aug 04 '15 at 06:10
0

There are two options:

  1. You can use curl, it is explained here : How can one check to see if a remote file exists using PHP?

  2. Use PHP file_exists() : http://php.net/manual/en/function.file-exists.php

Example :

$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;
}
Community
  • 1
  • 1
Arjun Komath
  • 2,802
  • 4
  • 16
  • 24
0

Try this

$ch = curl_init("https://www.google.com/images/srpr/logo11w.png");

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if($retcode==200)
    echo 'File Exist';
sujivasagam
  • 1,659
  • 1
  • 14
  • 26