php how to use getimagesize() to check image type on upload [duplicate]

谁都会走 提交于 2019-12-21 19:28:34

问题


Possible Duplicate:
GetImageSize() not returning FALSE when it should

i currently have a filter system as follows:

   // Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
    // This is an array that holds all the valid image MIME types
    $valid_types = array("image/jpg", "image/JPG", "image/jpeg", "image/bmp", "image/gif", "image/png");

    if (in_array($file['type'], $valid_types))
        return 1;
    return 0;
}

but i have been told that it is better to check the filetype myself, how would i use the getimagesize() to check the filetype in a similar way?


回答1:


getimagesize() returns an array with 7 elements. The index 2 of the array contains one of the IMAGETYPE_XXX constants indicating the type of the image.

The equivalent of the function provided using getimagesize() would be

function is_valid_type($file)
{
    $size = getimagesize($file);
    if(!$size) {
        return 0;
    }

    $valid_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);

    if(in_array($size[2],  $valid_types)) {
        return 1;
    } else {
        return 0;
    }
}



回答2:


You can use as below

$img_info   = getimagesize($_FILES['image']['tmp_name']);
$mime   = $img_info['mime']; // mime-type as string for ex. "image/jpeg" etc.



回答3:


Firstly check if getimagesize returns false. If it does, then the file is not a recognised image format (or not an image at all).

Otherwise, get index 2 of the returned array and run it through image_type_to_mime_type. This will return a string like "image/gif" etc. See the docs for more info.



来源:https://stackoverflow.com/questions/12761445/php-how-to-use-getimagesize-to-check-image-type-on-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!