Cargas de ficheros por método POST

Esta funcionalidad permite a las personas subir tanto texto como ficheros binarios. Con las funciones de identificación y manipulación de ficheros de PHP, se tiene el control total para definir quién tiene derecho a subir, pero también qué se hará con el fichero una vez que se haya subido.

PHP es capaz de recibir ficheros emitidos por un navegador conforme a la norma RFC-1867.

Nota: Notas de configuración

Véase también las directivas file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size y max_input_time en php.ini

PHP también soporta la carga por el método PUT como en el navegador Netscape Composer y Amaya del W3C. Consulte el capítulo sobre el soporte del método PUT.

Ejemplo #1 Formulario de carga de fichero

Un formulario de carga de ficheros puede ser construido creando un formulario específico como este:

<!-- El tipo de codificación de datos, enctype, DEBE ser especificado como se indica a continuación -->
<form enctype="multipart/form-data" action="_URL_" method="post">
  <!-- MAX_FILE_SIZE debe preceder al campo input de tipo file -->
  <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
  <!-- El nombre del elemento input determina el nombre en el array $_FILES -->
  Envíe este fichero: <input name="userfile" type="file" />
  <input type="submit" value="Enviar el fichero" />
</form>

_URL_ en el ejemplo anterior debe ser reemplazado y apuntar a un fichero PHP.

El campo oculto MAX_FILE_SIZE (medido en bytes) debe preceder al campo input de tipo file y su valor representa el tamaño máximo aceptado del fichero por PHP. Este elemento de formulario debe ser siempre utilizado, ya que permite informar al usuario que la transferencia deseada es demasiado grande antes de llegar al final de la carga. Tenga en cuenta que este parámetro puede ser "engañado" fácilmente desde el lado del navegador, por lo que no se debe confiar en él, tratándose finalmente de una funcionalidad de conveniencia del lado del cliente. El parámetro PHP (del lado del servidor) sobre el tamaño máximo de un fichero cargado, no puede ser engañado.

Nota:

Asegúrese de que su formulario de carga de fichero contenga enctype="multipart/form-data", de lo contrario, el fichero no será cargado.

La variable global $_FILES contendrá toda la información sobre el fichero cargado. Su contenido se detalla en nuestro ejemplo a continuación. Tenga en cuenta que se supone que el nombre de la variable del fichero cargado es userfile, tal como se define en el formulario anterior, pero puede ser cualquier nombre.

$_FILES['userfile']['name']

El nombre original del fichero, tal como en la máquina del cliente web.

$_FILES['userfile']['type']

El tipo MIME del fichero, si el navegador ha proporcionado esta información. Por ejemplo, esto podría ser "image/gif". Este tipo mime no es verificado por PHP y, por lo tanto, no se debe tomar su valor para sincronizarse.

$_FILES['userfile']['size']

El tamaño, en bytes, del fichero cargado.

$_FILES['userfile']['tmp_name']

El nombre temporal del fichero que será cargado en la máquina servidor.

$_FILES['userfile']['error']

El código de error asociado a la carga del fichero.

$_FILES['userfile']['full_path']

La ruta completa tal como se envía por el navegador. Este valor no contiene siempre una verdadera jerarquía de carpetas, y no se debe confiar en él. Disponible a partir de PHP 8.1.0.

El fichero cargado será almacenado temporalmente en el directorio temporal del sistema, a menos que se proporcione otro directorio con la directiva upload_tmp_dir del php.ini. El directorio por defecto del servidor puede ser cambiado en el entorno a través de la variable TMPDIR. Modificar el valor de esta variable con la función putenv() en un script PHP será sin efecto. Esta variable de entorno también puede ser utilizada para asegurarse de que otras operaciones funcionen también en los ficheros cargados.

Ejemplo #2 Validación de carga de ficheros

Véase también las funciones is_uploaded_file() y move_uploaded_file() para más información. El siguiente ejemplo cargará un fichero desde un formulario.

<?php
$uploaddir
= '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo
'<pre>';
if (
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo
"El fichero es válido, y ha sido cargado con éxito. Aquí hay más información :\n";
} else {
echo
"Ataque potencial por carga de ficheros. Aquí hay más información :\n";
}

echo
'Aquí hay algunas informaciones de depuración :';
print_r($_FILES);

echo
'</pre>';

?>

El script PHP que recibe el fichero cargado debe poder gestionar el fichero de manera apropiada. Se puede utilizar la variable $_FILES['userfile']['size'] para recalar todos los ficheros que son demasiado grandes o demasiado pequeños. Se puede utilizar la variable $_FILES['userfile']['type'] para descartar los ficheros que no tienen el tipo correcto, pero utilizarla únicamente para una serie de verificaciones, ya que este valor está completamente bajo el control del cliente y no es verificado por PHP. Se puede utilizar la información en $_FILES['userfile']['error'] y adaptar su política en función de los códigos de error. Sea cual sea su política, se debe borrar el fichero del directorio temporal o moverlo.

Si no se selecciona ningún fichero en el formulario, PHP devolverá 0 en $_FILES['userfile']['size'] y nada en $_FILES['userfile']['tmp_name'].

El fichero será borrado automáticamente del directorio temporal al final del script, si no ha sido movido o renombrado.

Ejemplo #3 Envío de un array de ficheros

PHP soporta los arrays en HTML así como con los ficheros.

<form action="" method="post" enctype="multipart/form-data">
<p>Imágenes:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Enviar" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if (
$error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() puede prevenir los ataques "filesystem traversal";
// otra validación/limpieza del nombre de fichero puede ser apropiada
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "data/$name");
}
}
?>

La barra de progreso de carga puede ser implementada utilizando la progresión de la carga a través de las sesiones.

add a note

User Contributed Notes 9 notes

up
89
daevid at daevid dot com
15 years ago
I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)

[1] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] =>
)
)

and not this
Array
(
[name] => Array
(
[0] => facepalm.jpg
[1] =>
)

[type] => Array
(
[0] => image/jpeg
[1] =>
)

[tmp_name] => Array
(
[0] => /tmp/phpn3FmFr
[1] =>
)

[error] => Array
(
[0] => 0
[1] => 4
)

[size] => Array
(
[0] => 15476
[1] => 0
)
)

Anyways, here is a fuller example than the sparce one in the documentation above:

<?php
foreach ($_FILES["attachment"]["error"] as $key => $error)
{
$tmp_name = $_FILES["attachment"]["tmp_name"][$key];
if (!
$tmp_name) continue;

$name = basename($_FILES["attachment"]["name"][$key]);

if (
$error == UPLOAD_ERR_OK)
{
if (
move_uploaded_file($tmp_name, "/tmp/".$name) )
$uploaded_array[] .= "Uploaded file '".$name."'.<br/>\n";
else
$errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."'<br/>\n";
}
else
$errormsg .= "Upload error. [".$error."] on file '".$name."'<br/>\n";
}
?>
up
46
mpyw
8 years ago
Do not use Coreywelch or Daevid's way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.

The following example form breaks their codes:

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[x][y][z]">
<input type="submit">
</form>

As the solution, you should use PSR-7 based zendframework/zend-diactoros.

GitHub:

https://github.com/zendframework/zend-diactoros

Example:

<?php

use Psr\Http\Message\UploadedFileInterface;
use
Zend\Diactoros\ServerRequestFactory;

$request = ServerRequestFactory::fromGlobals();

if (
$request->getMethod() !== 'POST') {
http_response_code(405);
exit(
'Use POST method.');
}

$uploaded_files = $request->getUploadedFiles();

if (
!isset(
$uploaded_files['files']['x']['y']['z']) ||
!
$uploaded_files['files']['x']['y']['z'] instanceof UploadedFileInterface
) {
http_response_code(400);
exit(
'Invalid request body.');
}

$file = $uploaded_files['files']['x']['y']['z'];

if (
$file->getError() !== UPLOAD_ERR_OK) {
http_response_code(400);
exit(
'File uploading failed.');
}

$file->moveTo('/path/to/new/file');

?>
up
24
coreywelch+phpnet at gmail dot com
9 years ago
The documentation doesn't have any details about how the HTML array feature formats the $_FILES array.

Example $_FILES array:

For single file -

Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)

Multi-files with HTML array feature -

Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)

[type] => Array
(
[0] => application/msword
[1] => application/msword
)

[tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)

[error] => Array
(
[0] => 0
[1] => 0
)

[size] => Array
(
[0] => 0
[1] => 0
)

)

)

The problem occurs when you have a form that uses both single file and HTML array feature. The array isn't normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.

<?php

function normalize_files_array($files = []) {

$normalized_array = [];

foreach(
$files as $index => $file) {

if (!
is_array($file['name'])) {
$normalized_array[$index][] = $file;
continue;
}

foreach(
$file['name'] as $idx => $name) {
$normalized_array[$index][$idx] = [
'name' => $name,
'type' => $file['type'][$idx],
'tmp_name' => $file['tmp_name'][$idx],
'error' => $file['error'][$idx],
'size' => $file['size'][$idx]
];
}

}

return
$normalized_array;

}

?>

The following is the output from the above method.

Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

)

[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

[1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

)

)
up
10
fravadona at gmail dot com
5 years ago
mpyw is right, PSR-7 is awesome but a little overkill for simple projects (in my opinion).

Here's an example of function that returns the file upload metadata in a (PSR-7 *like*) normalized tree. This function deals with whatever dimension of upload metadata.

I kept the code extremely simple, it doesn't validate anything in $_FILES, etc... AND MOST IMPORTANTLY, it calls array_walk_recursive in an *undefined behaviour* way!!!

You can test it against the examples of the PSR-7 spec ( https://www.php-fig.org/psr/psr-7/#16-uploaded-files ) and try to add your own checks that will detect the error in the last example ^^

<?php
/**
* THIS CODE IS ABSOLUTELY NOT MEANT FOR PRODUCTION !!! MAY ITS INSIGHTS HELP YOU !!!
*/
function getNormalizedFiles()
{
$normalized = array();

if ( isset(
$_FILES) ) {

foreach (
$_FILES as $field => $metadata ) {

$normalized[$field] = array(); // needs initialization for array_replace_recursive

foreach ( $metadata as $meta => $data ) { // $meta is 'tmp_name', 'error', etc...

if ( is_array($data) ) {

// insert the current meta just before each leaf !!! WRONG USE OF ARRAY_WALK_RECURSIVE !!!
array_walk_recursive($data, function (&$v,$k) use ($meta) { $v = array( $meta => $v ); });

// fuse the current metadata with the previous ones
$normalized[$field] = array_replace_recursive($normalized[$field], $data);

} else {
$normalized[$field][$meta] = $data;
}
}
}
}
return
$normalized;
}
?>
up
15
anon
9 years ago
For clarity; the reason you would NOT want to replace the example script with
$uploaddir = './';
is because if you have no coded file constraints a nerd could upload a php script with the same name of one of your scripts in the scripts directory.

Given the right settings and permissions php-cgi is capable of replacing even php files.

Imagine if it replaced the upload post processor file itself. The next "upload" could lead to some easy exploits.

Even when replacements are not possible; uploading an .htaccess file could cause some problems, especially if it is sent after the nerd throws in a devious script to use htaccess to redirect to his upload.

There are probably more ways of exploiting it. Don't let the nerds get you.

More sensible to use a fresh directory for uploads with some form of unique naming algorithm; maybe even a cron job for sanitizing the directory so older files do not linger for too long.
up
15
eslindsey at gmail dot com
16 years ago
Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients' side. You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client. This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst).
up
8
Mark
14 years ago
$_FILES will be empty if a user attempts to upload a file greater than post_max_size in your php.ini

post_max_size should be >= upload_max_filesize in your php.ini.
up
6
claude dot pache at gmail dot com
16 years ago
Note that the MAX_FILE_SIZE hidden field is only used by the PHP script which receives the request, as an instruction to reject files larger than the given bound. This field has no significance for the browser, it does not provide a client-side check of the file-size, and it has nothing to do with web standards or browser features.
up
0
rrueda at silegonline dot com
2 months ago
It's not necessary to write multiple input fields in the form to upload multiple files, this way, with only one input also works:

<input type="file" name="nomfile[]" multiple>
To Top