Search code examples
phptimeoutgetimagesize

Remote PHP getimagesize()/ Check if exist


I am using getimagesize() to collect image information loaded remotely.

The problem is if the remote server takes too long on the request or the image doesn't exist and I get an error timeout. What can I do to prevent this, so that if it takes 15 seconds to load automatically make the request then return some code returning null $width, $height, and $type?

if($siteImage != "None"){
list($width, $height, $type) = getimagesize($siteImage);
if(!filter_var($siteImage, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)){
    die("fillDiv('checkImage','<font color=\"red\">Image is not valid URL type.</font>');");
}elseif($width != "468" || $height != "60"){
    die("fillDiv('checkImage','<font color=\"red\">Incorrect size.</font>');");
}elseif($type != "1" && $type != "2" && $type != "3"){
    die("fillDiv('checkImage','<font color=\"red\">Incorrect image type. (.jpg .gif .png) only</font>');");
}else{
    print("fillDiv('checkImage','');");
}
}

Solution

  • You have two options.

    1 Use getimagesize but in two lines, and hide error messages. Check for a return value

    $aSize = @getimagesize($url);
    if ($aSize) {
        // You have a return values
        list($width, $height, $type) = $aSize;
    } else {
        // No return values
        $width = 0;  // etc
    }
    

    2 User cUrl to copy the file locally. You can control the timeous better with curl, also you can check if the file exists or is taking too long to download etc. Once copied locally, use getimagesize() on the local file. It will only then fail if the file is not a genuine image. Quick online example: http://www.weberdev.com/get_example.php3?ExampleID=4009