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?
$_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.
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.
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.
The filesize() function returns the size of a file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With