📜 ⬆️ ⬇️

Setting the maximum file size upload via HTML form

Many people encountered a problem when uploading files, that the server persistently tries to download files that are too large for us and this process not only slows down the user, forcing him to wait for a long time, but also loads the server to which the file is downloading.

For Apache servers with PHP installed on them, you can limit this process to 2 ways:
  1. limit the file download settings PHP itself
  2. limit the file upload using the mechanisms for sending a form request to the server (only by the POST method)
If the first option is quite common among administrators and programmers, then the second, simpler (even one can say custom) is not very popular.

I would like to consider it.
So let's start with what we specify in the form method="post" and enctype="multipart/form-data" . Next, create a hidden form element.
<input type="hidden" name="MAX_FILE_SIZE" value="1111111">

In the value of the element MAX_FILE_SIZE we specify the maximum size we need in bytes of the downloaded files.
Special attention should be paid to the fact that this element should be BEFORE the file selection fields (for example, immediately after the form tag):
')
Example:
<form method="post" .... enctype="multipart/form-data">
<input type="hidden" name="max_file_size" value="1111111">
...
<input type="file" name="photo" >
...
</form>


What happens in practice (although some configurations of PHP and Apache prohibit this method):
PHP first gets our file size limit option. Then it reads its value, then “resets” the elements of the $ _FILES array, where the file size exceeds the required one.

An example of what he does with this element:
Array ( [photo] => Array ( [name] => my_photo.jpg [type] => [tmp_name] => [error] => 2 [size] => 0 )

As you can see, it sets an error code for this element that is different from 0 (0 = successful download), this error reads: “The uploaded file has exceeded the MAX_FILE_SIZE value set in HTML form.

Attention:
For more information about errors that the server can return, you can read on the PHP site .
detailed description of the mechanism on php.net

PS: I hope this article will help many coders, especially those who do not have server rights to change PHP settings on the server.

ZZY: In my topic, I just wanted to describe one of the mechanism and my experience in using it. This is by no means NOT a manual for compulsory actions, since it is merely an additional , in some cases convenient, verification mechanism.

ZZZY: Edited taking into account statements, wishes, disputes and advice in the comments.

Source: https://habr.com/ru/post/69532/


All Articles