Progreso de Subida en Sesiones

Cuando la opción INI session.upload_progress.enabled está habilitada, PHP podrá rastrear el progreso de subida de ficheros individuales que están siendo subidos. Esta información no es particularmente útil para la petición de subida real en sí misma, pero durante la subida del archivo, una aplicación puede enviar una petición POST a un nodo distinto (mediante XHR por ejemplo) para comprobar el estado.

El progreso de subida estará disponible en la variable superglobal $_SESSION cuando una subida está en progreso, y al usar POST con una variable con el mismo nombre al que está establecido el ajuste INI session.upload_progress.name. Cuando PHP detecta tales peticiones POST, rellenará un array en la variable $_SESSION, donde el índice es un valor concatenado de las opciones INI session.upload_progress.prefix y session.upload_progress.name. La clave se recupera normalmente leyendo estas opciones INI, es decir

<?php
$clave 
ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$clave]);
?>

También es posible cancelar la subida de ficheros que está en progreso, estableciendo la clave $_SESSION[$clave]["cancel_upload"] a TRUE. Cuando se suben múltiples ficheros en la misma petición, esto solamente cancelará la subida de ficheros que está en progreso, y las subidas de ficheros pendientes, pero no eliminará de manera satisfactoria las subidas completadas. Cuando una subida se cancela de esta manera, la clave error del array $_FILES será establecida a UPLOAD_ERR_EXTENSION.

Las opciones INI session.upload_progress.freq y session.upload_progress.min_freq controlan con qué frecuencia debería ser recalculada la información del progreso de subida. Con una cantidad razonable de estos dos ajustes, la sobrecarga de esta característica es casi inexistente

Ejemplo #1 Ejemplo de información

Ejemplo de la esctructura del array del progreso de subida.

<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>

La información almacenada en la sesión se parecerá a esta:

<?php
$_SESSION
["upload_progress_123"] = array(
 
"start_time" => 1234567890,   // El instante de la petición
 
"content_length" => 57343257// longitud del contenido de POST
 
"bytes_processed" => 453489,  // Cantidad de bytes recibidos y procesados
 
"done" => false,              // True cuando el gestor de POST ha finalizado, satisfactoriamente o no
 
"files" => array(
  
=> array(
   
"field_name" => "file1",       // nombre del campo <input/>
   // Los siguientes 3 elementos son iguales que aquellos de $_FILES
   
"name" => "foo.avi",
   
"tmp_name" => "/tmp/phpxxxxxx",
   
"error" => 0,
   
"done" => true,                // True cuando el gestor de POST ha terminado de manejar este fichero
   
"start_time" => 1234567890,    // Cuándo se empezo a procesar este fichero
   
"bytes_processed" => 57343250// Número de bytes recibidos y procesados de este fichero
  
),
  
// Otro fichero, no terminado de subir, en la misma petición
  
=> array(
   
"field_name" => "file2",
   
"name" => "bar.avi",
   
"tmp_name" => NULL,
   
"error" => 0,
   
"done" => false,
   
"start_time" => 1234567899,
   
"bytes_processed" => 54554,
  ),
 )
);

Advertencia

El almacenamiento en búfer de peticiones del servidor ha sido deshabilitado para que esto funcione apropiadamente, si no, PHP podría ver la subida de ficheros una vez realizada esta completamente. Los servidores como Nginx almacenan en búfer peticiones más grandes.

add a note add a note

User Contributed Notes 16 notes

up
95
s.zarges
4 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
21
howtomakeaturn
1 year 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
20
gerd dot randolf at web dot de
4 years ago
Note that this will be available from PHP 5.4 on. It won't work in PHP 5.3 or earlier.
up
12
Anonymous
3 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
2
ricki at rocker dot com
1 year ago
session.upload_progress updates completely ignore custom session handlers set via  session_set_save_handler()
up
10
isius
3 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
4
wojbach at o2 dot pl
4 years ago
"session.upload-progress.name" -> whether here shouldn't be a underscore instead of a dash
up
2
Anonymous
3 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
1
adri74 at hotmail dot fr
5 months ago
It seems like defining a session name before starting the session makes the $_SESSION['upload_progress...'] not to work any more !

session_name('session');
session_start();

(in both the upload page, and the XHR request)
up
0
alice at librelamp dot com
10 days 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
0
StrateGeyti
1 year 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
0
jortsc at gmail dot com
2 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
-2
nihaopaul at gmail dot com
3 years ago
it should be noted that the hidden element come before the file element otherwise you wont get any updates.
up
-3
wilsonr at st dot com
1 year ago
If you have upload progress enabled in your php.ini, and you have

<form enctype="multipart/form-data" ...
    <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" ...

in your form, but you DON'T specify an input with 'type="file"', you may lose your session ID. I am using PHP 5.5 and I lose my session ID on the second loading of such a page. To prevent this, you can use a dummy input as follows:

<form enctype="multipart/form-data" ... >
    <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" ... />
    <input type="file"' name="dummy" style="display="none;" ... />
up
-20
takeone
4 years ago
IE6 does not inherit session when you launch new browser from start menu or shortcut.It's the feature.
It is recommended that upload form and progress bar are on same window.
To Top