简体   繁体   中英

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?

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.

PHP does seem to recalculate the size of the file after it is uploaded. Although the client does send a header specifying the content-length of the file, based on tests (with PHP 5.5) this header is simply ignored and, instead, the length is measured. Personally, I would always use filesize() to get the file size since you can be more confident about which measurement is being used, but it is ultimately up to you. Either way, $_FILES['file_name']['size'] appears to be a safe value to use.

You should rather check if the client-reported $_FILES['file_name']['size'] equals the value given by filesize() . A difference may indicate an error during transmission of the uploaded file.

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