文件大小错误代码无效

I have written below lines of code

<?php

$uniqId = uniqid('file_');
$root = $_REQUEST['root'];

$target_file = "uploads/".basename($_FILES["file"]["name"]);

$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

if ( 0 < $_FILES['file']['error'] )
{
    echo 'Error';
}
else if ($_FILES["file"]["size"] > 2097152) 
{
  echo "SizeError";
}
else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "docx" && $imageFileType != "pdf") 
{
  echo "ExtensionError";
}
else 
{   
   if( move_uploaded_file($_FILES['file']['tmp_name'], $root.$uniqId.".".$imageFileType))
   {
       echo $uniqId.".".$imageFileType;
   }
}

?>

If I upload 5 mb file, the code is jumped to simple "Error" condition. I want that it should display SizeError. Please help!!!

This is an alternative way to get size

if (filesize($target_file) > 2097152) 
{
  echo "SizeError";
}

But firstly I think there is an error UPLOAD_ERR_INI_SIZE at $_FILES['file']['error']. UPLOAD_ERR_INI_SIZE=1 You can increase it in php.ini. Add or modify this in your php.ini for example yo increase max_file_size = 25mb:

upload_max_filesize = 25M

After modifying php.ini your code should work too:

if ( 0 < $_FILES['file']['error'] )
{
    echo 'Error';
}
else if ($_FILES["file"]["size"] > 2097152) 
{
  echo "SizeError";
}

To check your php.ini settings call:

echo phpinfo();

You will see your settings, find upload_max_filesize it's 2mb as default value. Looks like this:

enter image description here

check this condition first if ($_FILES["file"]["size"] > 2097152) then check others.

You probably get the UPLOAD_ERR_INI_SIZE at $_FILES['file']['error'] which is qual to 1. You can increase it in php.ini. Change this in your php.ini:

upload_max_filesize = 25M

The reason you're getting "error" is because of this line:

if ( 0 < $_FILES['file']['error'] )

If you read the documentation here: PHP: Upload Error Messages Explained, then you'll notice that there are several values that can be returned with $_FILES['file']['error']. It returns 0 when there are no errors. But it returns 1 if

The uploaded file exceeds the upload_max_filesize directive in php.ini.

And it returns 2 if:

The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

In both cases 0 is smaller than 1 or 2. So your script is returning you "Error". Because the condition evaluates to true.

You need to either change the condition, or check for the file size first.