Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you trust file size given by $_FILES array in PHP?

Sorry if it is trivial or obvious, but I could not find the answer by googling it.

From where does the size value in $_FILES['name'] array come from? Could you trust the value of it ($_FILES['name']['size']) or should you still check it using the filesize() function?

In other words, is it necessary to check actual file size by filesize function to notice if it is properly uploaded?

like image 464
Ormoz Avatar asked May 03 '15 13:05

Ormoz


People also ask

What is the purpose of $_ files variable 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.

What type of information is stored by $_ files array?

The global predefined variable $_FILES is an associative array containing items uploaded via HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute set to multipart/form-data. $_FILES['file']['name'] - The original name of the file to be uploaded.

How will you get the size of a file in PHP?

To get the file size, we will use filesize() function. The filesize() function returns the size of a file in bytes. This function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure.

Which PHP function is used to get the size of the file?

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


1 Answers

If the file is uploaded correctly and everything is fine, you can use the info provided by PHP superglobal $_FILES. Using filesize() adds small overhead since OS needs to inspect the file for the size. It's up to you, but checking PHP source on how it does all this indicates clearly that it correctly calculates the file size in the HTTP multipart request. Basically, you'd be doing the same job again if you were to filesize() the file.

The reason you can trust this directly from superglobal variable is the fact that multipart requests supply a boundary between which the data resides. By definition, it's not possible to obtain corrupt data if the protocol for extracting the data isn't followed. In other words, it means that browser sends a "delimiter" and PHP simply finds it and starts checking the text for data between that delimiter. To do this, it accurately allocates required memory and it can immediately cache the number allocated - and that number is the file size. If anything is wrong along the way, you will get errors. Therefore, if the file uploaded correctly, the information about the size is trusted.

like image 127
N.B. Avatar answered Oct 13 '22 17:10

N.B.