我可以用任何方式检查url是否指向有效图像(使用JS / PHP / ZendFramework)?

i am developing a test/learning app. i wonder how can i test if an image from another site/domain ... i broke up my validation logic to the following

  • exists
  • is an image
  • is of valid type
  • is of a specific dimensions
  • is below a max size - say i want the image to load quickly. tho the hosting resource is not mine.

getimagesize() can do all but the last of your points. For that you can use filesize(). For filesize() you'll have to actually download it though, but seeing as getimagesize() also requires that, you can just save it to a temporary file. You can use tempnam() to get a temporary file that doesn't conflict with others.

  1. checking if url exists:

    $handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($handle); $status = curl_getinfo($handle, CURLINFO_HTTP_CODE); if($status == 404) {//return true or whatever}

  2. is an image, is of valid type: determine if the file extension is valid, for example using

    preg_match('/(jp[e]?g|png|gif|etc...)$/i', $url);

  3. is of specific dimensions: use GD to create a resource and then check size by getImageSize($resource)

  4. is below max size: in addition to step 1 - $size = curl_getinfo($handle, CURLINFO_SIZE_DOWNLOAD);

Remember that you must have cURL and GD enabled.