Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_FILES["file"]["size"] returning 0?

Tags:

I am trying to upload something using PHP and set a limit on the total size that I allow to be uploaded. I want to limit my uploads to 2MB but for some reason whenever I try to check with an if statement like this:

if (($_FILES["file"]["size"] < 2097152))

A file that is large (such as a 7mb file) will pass through the if statement because for whatever reason if I print $_FILES["file"]["size"], it will return 0, instead of the proper number of bytes. If I try to upload something that is smaller, like 342kb the $_FILES["file"]["size"] will return the proper size.

Is there anyway to get $_FILES["file"]["size"] to actually hold the proper size of the file? Otherwise I do not know how to fix this problem.

like image 959
user494216 Avatar asked Oct 31 '11 20:10

user494216


People also ask

What is $_ files [' file Tmp_name ']?

$_FILES['file']['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server.

What does $_ files do in PHP?

$_FILES is a super global variable which can be used to upload files. Here we will see an example in which our php script checks if the form to upload the file is being submitted and generates a message if true. Code of files.

Which returns size of the file in PHP?

The filesize() function returns the size of a file.

How can get upload file size in PHP?

The filesize() function in PHP is an inbuilt function which is used to return the size of a specified file. The filesize() function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure.


2 Answers

A file which aborts for any reason (upload failed, exceeds limits, etc...) will show as size 0

You have to check for upload SUCCESS before you do ANYTHING with the rest of th eupload data:

if(array_key_exists('file', $_FILES)){     if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {        echo 'upload was successful';     } else {        die("Upload failed with error code " . $_FILES['file']['error']);     } } 

The error codes are defined here. In your case, if you've hardcoded a 2meg limit and someone uploads a 2.1 meg file, then the error code would be UPLOAD_ERR_INI_SIZE (aka 2), which is "exceeds limit set in .ini file".

like image 169
Marc B Avatar answered Nov 24 '22 04:11

Marc B


if( $_FILES['file']['size'] && $_FILES['file']['size'] < (2<<20))

Try that.

<< is bitwise shift operator, decimal 2 is binary "10", then add 20 zeros.

like image 37
Niet the Dark Absol Avatar answered Nov 24 '22 04:11

Niet the Dark Absol