Manish Chauhan
Manish Chauhan

Reputation: 570

How to check if Image exists on server using URL

I am trying to check whether image file is exist on server Or not. I am getting image path with other server.

Please check below code which I've tried,

$urlCheck = getimagesize($resultUF['destination']);

if (!is_array($urlCheck)) {
  $resultUF['destination'] = NULL;
}

But, it shows below warning

Warning: getimagesize(http://www.example.com/example.jpg) [function.getimagesize]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in

Is there any way to do so?

Thanks

Upvotes: 0

Views: 5987

Answers (6)

Hassan Saeed
Hassan Saeed

Reputation: 7080

Fastest & efficient Solution for broken or not found images link
i recommend you that don't use getimagesize() because it will 1st download image then it will check images size+if this will not image then it will throw exception so use below code

if(checkRemoteFile($imgurl))
{
//found url, its mean
echo "this is image";
}

function checkRemoteFile($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    // don't download content
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(curl_exec($ch)!==FALSE)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Note: this current code help you to identify broken or not found url image this will not help you to identify image type or headers

Upvotes: 1

Bora
Bora

Reputation: 10717

Use fopen function

if (@fopen($resultUF['destination'], "r")) {
    echo "File Exist";
} else {
    echo "File Not exist";
}

Upvotes: 0

Harshal
Harshal

Reputation: 3622

You need to check that the file is exist regularly on server or not.you should used:

is_file .For example

$url="http://www.example.com/example.jpg";

if(is_file($url))
{
echo "file exists on server";
}
else
{
echo "file not exists on server ";
}

Upvotes: 1

DevZer0
DevZer0

Reputation: 13535

you can use file_get_contents. This will cause php to issue a warning along side of returning false. You may need to handle such warning display to ensure the user interface doesn't get mixed up with it.

 if (file_get_contents($url) === false) {
       //image not foud
   }

Upvotes: 0

William Buttlicker
William Buttlicker

Reputation: 6000

$url = 'http://www.example.com/example.jpg)';
print_r(get_headers($url));

It will give an array. Now you can check the response to see if image exists or not

Upvotes: 3

Issue is that the image may not exist or you don't have a direct permission for accessing the image, else you must be pointing an invalid location to the image.

Upvotes: 0

Related Questions