简体   繁体   中英

Error in php error handling (file upload)

I want to put out an error message when the uploaded image size is over 3MB. This is my current code. It should put out an error message when an image is over 3MB, but it does nothing. What's wrong with my code?

if ( $_FILES['file']['size'] != 0 ) 
{
 //image check start
 if ((($_FILES["file"]["type"] == "image/gif")
 || ($_FILES["file"]["type"] == "image/jpeg")
 || ($_FILES["file"]["type"] == "image/png")
 || ($_FILES["file"]["type"] == "image/pjpeg"))
 && ($_FILES["file"]["size"] < 3072000))
 //image check end
 {
      if (file_exists($upload_path."/".$_FILES["file"]["name"])) 
      {
           $file_tmp = $_FILES["file"]["name"];
      } //Link if there is already a file with identical file name
      else
      {
           $photoid = $upfile_idx.".".substr($_FILES['file']['name'],-3);
           move_uploaded_file($_FILES["file"]["tmp_name"], $upload_path."/".$photoid);
           $file_tmp = $photoid ;
      } //Upload the image file into upload folder and generate an id for the image
  }
  else
  {
      error("Maximum image size exceeded or invalid file format.");
  }
}

//insert $file_tmp into database here

----------
Error code (added later)
function error($msg)
{
  echo "<script>alert(\"$msg\");history.go(-1);</script>";
  exit;
}

I've found what's wrong. In my php.ini file, there was 'upload_max_filesize = 3M' and obviously that's what was causing all the problem. When I changed it to 'upload_max_filesize = 4M', everything worked just fine. Thank you all for your help.

Something on the following should do you good.

<?php 
if ( $_FILES['file']['size'] != 0 ) 
{
 //image check start

 if(!in_array($_FILES["file"]["type"], array("image/gif", "image/jpeg", "image/png", "image/pjpeg")))
 {
    error("File should be a JPG/JPEG/PNG/PJEPG only");
    return; 
 }
 if($_FILES["file"]["size"] > 3145728)
 {
    error("File should be less than 3 MB");   
    return; 
 }
 #Rest of your upload code should go below here.
}
?>

3145728 translates to 3 MB in bytes since $_FILES["file"]["size"] gives the size of the file being uploaded in bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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