简体   繁体   English

如何在php中检查上传的图片大小是否大于2MB?

[英]how to check uploaded image size is greater than 2MB in php?

I am working on image compression in php. 我正在使用php进行图像压缩。

 <?php if ($_POST) { echo $_FILES['file']['size']; } ?> <html> <head><title>Php code compress the image</title></head> <body> <form action="" name="myform" id="myform" method="post" enctype="multipart/form-data"> <ul> <li> <label>Upload:</label> <input type="file" name="file" id="file"/> </li> <li> <input type="submit" name="submit" id="submit" class="submit btn-success"/> </li> </ul> </form> </body> </html> 

This is working fine with the images less than 2MB. 对于小于2MB的图像,这可以正常工作。

if size>2MB then even its not showing in $_FILES after clicking on the submit button 如果大小> 2MB,则在单击“提交”按钮后,即使它没有显示在$_FILES

You first problem is that you're not checking if an upload was successful. 您的第一个问题是您没有检查上传是否成功。 You cannot use ANYTHING in $_FILES until you've checked for that error. 您必须先检查该错误,然后才能在$ _FILES中使用任何内容。 And checking for $_POST is not "error checking". 并且检查$ _POST不是“错误检查”。

At bare minimum you should have 至少您应该有

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        die("Upload failed with error code " . $_FILES['file']['error']);
   }
   ... got here, upload was successful
}

You can check $_FILES['file']['error'] and check if it's value is equal to the magic constant UPLOAD_ERR_INI_SIZE 您可以检查$_FILES['file']['error']并检查其值是否等于魔术常数UPLOAD_ERR_INI_SIZE

if ($_FILES['file']['error'] === UPLOAD_ERR_INI_SIZE) { 
    //uploading failed due to size limmit
} 

This is probably due to the "upload_max_filesize" and/or "max_post_size" setting. 这可能是由于“ upload_max_filesize”和/或“ max_post_size”设置所致。 Check for the setting in your php.ini. 检查您的php.ini中的设置。

You can use this if the uploaded size is greater than 2 mb it shows an error 如果上传的大小大于2 mb,则显示错误,可以使用此选项

if($file_size > 2048) {
    $errors[]='File size is greater than 2 MB';
}

Or if you want to upload image size more than 2 mb then edit your php.ini file and change "upload_max_filesize" and/or "max_post_size" value. 或者,如果您要上传大于2 mb的图片,请编辑php.ini文件并更改“ upload_max_filesize”和/或“ max_post_size”值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM