PHP Image Upload Checking Dimensions

岁酱吖の 提交于 2019-12-20 03:47:09

问题


How can I check the dimensions of an image after it has uploaded and delete it if it does not match the dimensions I want?

So after digging around I find PHP cannot do dimensions. The solution I am following is:

  1. Upload the file to the server
  2. Use that new string and check
  3. Delete it or continue with upload if it does not match width and height

This is my code. Can someone show me how to check the current file for dimensions and how to delete the folder and file if not matching?

# create our temp dir
    mkdir("./uploads/temp/".$user."/".$mx."/".$hash."/", 0777, true);
    # upload dir settup
    $uploaddir='./uploads/temp/'.$user.'/'.$mx.'/'.$hash.'/';
    $file=$uploaddir . basename($_FILES['file']['name']);

    # upload the file first
    if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
        # ok so check the height and width
        # if it is not the width and height assigned delete image and folder
        if (image height= and width =){
            unlink($file);
            rmdir($uploaddir);
            $result=0;
        } else {
        # image matches height and width message ok
            $result=1;
        }
    } else {
        # error uploading
        $result=$errormsg;
    }

回答1:


mkdir("./uploads/temp/".$user."/".$mx."/".$hash."/", 0777, true);
# upload dir settup
$uploaddir='./uploads/temp/'.$user.'/'.$mx.'/'.$hash.'/';
$file=$uploaddir . basename($_FILES['file']['name']);

# upload the file first
if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
    # ok so check the height and width
    # if it is not the width and height assigned delete image and folder
    $size = getimagesize($files);
    $maxWidth = 500;
    $maxHeight = 500;
    if ($size[0] > $maxWidth || $size[1] > $maxHeight)
    {
        unlink($file);
        rmdir("./uploads/temp/".$user."/".$mx."/".$hash."/");
        rmdir("./uploads/temp/".$user."/".$mx."/");
        rmdir("./uploads/temp/".$user."/");
    }
    else
        $result=1;
    end if
} else {
    # error uploading
    $result=$errormsg;
}



回答2:


I use the getimagesize function with GD library.

Example usage:

list($width, $height, $type, $attr) = @getimagesize($imageUri);

if (($height > 500) && ($width > 500)) {
    throw new Exception(sprintf('Invalid image: %d(h) and %d(w) are not within tolerable range', $height, $width));
}



回答3:


For getting dimension Very Simple and easy with temp_file

$image_info = getimagesize($_FILES["file_field_name"]["tmp_name"]);
$image_width = $image_info[0];
$image_height = $image_info[1];



回答4:


What about this? http://php.net/manual/en/function.getimagesize.php

http://php.net/manual/en/function.rmdir.php

To delete the folder, it should be empty.



来源:https://stackoverflow.com/questions/9317842/php-image-upload-checking-dimensions

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