Check whether image exists on remote URL

2019-01-04 01:16发布

I am generating dynamic URLs of images for book ISBNs. I need a reliable way with PHP to check whether the images actually exist at the remote url. I tried various approaches with different PHP libraries, curl, etc., but none of them works well, some of them are downright slow. Given the fact that I need to generate (and check!) about 60 URLS for each book in my database, this is a huge waiting time. Any clues?

标签: php url image curl
8条回答
仙女界的扛把子
2楼-- · 2019-01-04 01:55

There is no "easy" way here - at a very minimum, you need to generate a HEAD request and check the resulting content type to make sure it's an image. That's not taking into account possible referrer issues. curl is the way to go here.

查看更多
乱世女痞
3楼-- · 2019-01-04 01:57

You could use curl. Just set the curl option CURLOPT_NOBODY to true. This will skip body information and only get the head (thus http code as well). Then, you could use the CURLOPT_FAILONERROR to turn this whole process into a true/false type check

查看更多
可以哭但决不认输i
4楼-- · 2019-01-04 01:57

It's probably a mute point at this point, but this works for me:

function is_webfile($webfile)
{
 $fp = @fopen($webfile, "r");
 if ($fp !== false)
  fclose($fp);

 return($fp);
}
查看更多
做个烂人
5楼-- · 2019-01-04 01:57

If the images all exist on the same remote server (or in the same network), you could run a web service on that server that will check the file system for the the image file and return a bool value indicating wheter the image exists or not.

查看更多
趁早两清
7楼-- · 2019-01-04 02:03

Use getimagesize() method like this

$external_link = ‘http://www.example.com/example.jpg’;
if (@getimagesize($external_link)) {
echo  “image exists “;
} else {
echo  “image does not exist “;
}
查看更多
登录 后发表回答