PHP 8.4.0 RC3 available for testing

Отслеживание хода загрузки файлов через сессии

PHP умеет отслеживать ход загрузки отдельных файлов, если включить INI-директиву session.upload_progress.enabled. Эта информация не приносит пользы самому запросу на отправку файла, но во время загрузки файла приложение может отправить POST-запрос отдельной конечной точке, например через интерфейс XHR, чтобы проверить статус.

Ход загрузки будет доступен в суперглобальной переменной $_SESSION по мере загрузки файла, и при отправке POST-переменной с тем же именем, которое установили для INI-параметра session.upload_progress.name. Когда PHP обнаруживает такие POST-запросы, он заполняет в переменной $_SESSION массив, в котором ключом будет конкатенация значений опций session.upload_progress.prefix и session.upload_progress.name. Ключ обычно получают путём чтения значений этих директив, то есть:

<?php

$key
= ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$key]);

?>

Разработчики отменяют текущую загрузку файла через установку для ключа $_SESSION[$key]["cancel_upload"] значения true, когда требуется. При загрузке набора файлов в одном запросе этот способ отменит только текущую загрузку файла, которая уже началась, и загрузки в очереди, но не удалит загрузки, которые уже завершились. При отмене загрузки таким способом PHP установит элементу массива $_FILES с ключом error значение константы UPLOAD_ERR_EXTENSION.

Директивы session.upload_progress.freq и session.upload_progress.min_freq определяют, как часто требуется обновлять информацию о ходе загрузки. Накладные расходы на эту функцию не ощущаются при разумных значениях этих настроек.

Пример #1 Пример информации

Пример структуры массива прогресса загрузки.

<form action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
    <input type="file" name="file1" />
    <input type="file" name="file2" />
    <input type="submit" />
</form>

Данные, которых хранятся в сессии, будут выглядеть вот так:

<?php

<?php

$_SESSION
["upload_progress_123"] = array(
"start_time" => 1234567890, // Время начала запроса
"content_length" => 57343257, // Длина содержимого POST-запроса
"bytes_processed" => 453489, // Количество байтов, которые получил и обработал запрос
"done" => false, // После завершения обработки POST-запроса значение изменится на true,
// независимо от того, успешно или нет завершилась обработка
"files" => array(
0 => array(
"field_name" => "file1", // Значение атрибута name поля <input/>
// Следующие 3 элемента соответствуют элементам суперглобального массива $_FILES
"name" => "foo.avi",
"tmp_name" => "/tmp/phpxxxxxx",
"error" => 0,
"done" => true, // Элемент получает значение true, когда обработчик POST-запроса
// закончил обработку файла
"start_time" => 1234567890, // Время начала обработки файла
"bytes_processed" => 57343250, // Количество байтов, которые запрос получил и обработал для файла
),
// Ещё один файл, загрузка которого ещё не закончилась в том же запросе
1 => array(
"field_name" => "file2",
"name" => "bar.avi",
"tmp_name" => NULL,
"error" => 0,
"done" => false,
"start_time" => 1234567899,
"bytes_processed" => 54554,
),
)
);

?>

Внимание

Для правильной работы требуется отключить буферизацию запросов веб-сервера, иначе PHP увидит загрузку файла только после полной загрузки. Серверы наподобие Nginx буферизуют большие запросы.

Предостережение

Информация о ходе загрузки записывается в сессию перед выполнением скриптов. Поэтому PHP начнёт сессию без информации о ходе загрузки, если изменить название сессии функцией ini_set() или session_name().

Добавить

Примечания пользователей 11 notes

up
165
s.zarges
12 years ago
Note, this feature doesn't work, when your webserver is runnig PHP via FastCGI. There will be no progress informations in the session array.
Unfortunately PHP gets the data only after the upload is completed and can't show any progress.

I hope this informations helps.
up
63
howtomakeaturn
9 years ago
ATTENTION:

Put the upload progress session name input field BEFORE your file field in the form :

<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
<input type="file" name="file1" />
<input type="file" name="file2" />
<input type="submit" />
</form>

If you make it after your file field, you'll waste a lot of time figuring why (just like me ...)

The following form will make you crazy and waste really a lot of time:

<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file1" />
<input type="file" name="file2" />
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
<input type="submit" />
</form>

DON'T do this!
up
24
Anonymous
11 years ago
While the example in the documentation is accurate, the description is a bit off. To clarify:

PHP will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and the VALUE of the POSTed session.upload_progress.name variable.
up
14
isius
12 years ago
If you're seeing
"PHP Warning: Unknown: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in Unknown on line 0",
then a misplaced input could be the cause. It's worth mentioning again that the hidden element MUST be before the file elements.
up
6
jortsc at gmail dot com
11 years ago
Note that if you run that code and you print out the content of $_SESSSION[$key] you get an empty array due that session.upload_progress.cleanup is on by default and it cleans the progress information as soon as all POST data has been read.

Set it to Off or 0 to see the content of $_SESSION[$key].
up
5
nihaopaul at gmail dot com
12 years ago
it should be noted that the hidden element come before the file element otherwise you wont get any updates.
up
2
alice at librelamp dot com
8 years ago
There were two gotchas that got me with implementing this.

The first - if you use session_name() to change the name of sessions, this will not work. I discovered this by looking at phpinfo() and seeing that is saw a different session name.

At least in Apache, a better way to set the session is in your apache config use

php_value session.name "your custom name"

It goes within the Directory directive, might work in .htaccess - I don't know.

-=-

Secondly - in apache, don't use mod_mpm_prefork.so

That was the problem I had, that's the default in CentOS 7.

The problem is it causes Apache to wait with any additional requests until the upload is finished.

Commenting that module out and using mod_mpm_worker.so instead fixed that problem, and the progress meter worked.
up
3
Anonymous
11 years ago
dont't forget, that the session has to be initialized before the form is generated, otherwise the mentioned example above won't work.
up
0
raptor98 at email dot cz
1 month ago
Warning:
Do not change session.save_path and session.name (in your application)!

The request for upload info must by POST with same value and name of your hidden input (session.upload_progress.name).

Info:
It works under IIS /FastCGI (at PHP 5.4 and PHP 8.2, other not tested).
up
1
StrateGeyti
10 years ago
It seems like if you send a form with the field like :

<?php echo '<input type="hidden" name="'.ini_get('session.upload_progress.name') .'" value="123" />'; ?>

without any field type "file", the server respons will be an 500 error.
up
1
ricki at rocker dot com
9 years ago
session.upload_progress updates completely ignore custom session handlers set via session_set_save_handler()
To Top