PHP Detecting if source image url link leads to a “broken” image?

前端 未结 8 1542
迷失自我
迷失自我 2020-12-30 03:56

Suppose you have a thumbnail generator script that accepts source images in the form of a URL. Is there a way to detect if the source URL is \"broken\" - whether nonexistent

相关标签:
8条回答
  • 2020-12-30 04:47
    try for local files
    
    <?php 
    if(file_exists($filename))
    {
    //do what you want
    }
    else
    {
    //give error that file does not exists
    }
    ?>
    

    for external domains

    $headers = @get_headers($url);
    if (preg_match("|200|", $headers[0])) {
    // file exists
    } else {
    // file doesn't exist
    }
    

    Also you can use curl request for the same.

    0 讨论(0)
  • 2020-12-30 04:57

    You could check the HTTP status code (it should be 200) and the Content-type header (image/png etc.) of the HTTP response before you put the actual image through the generator.

    If these two preconditions are ok, after retrieving the image you can call getimagesize() on it and see if it breaks, what MIME type it returns etc.

    0 讨论(0)
提交回复
热议问题