Subiendo archivos al servidor

29.05.19

Considere subir archivos a un servidor PHP usando el método POST. Esto requerirá un formulario con el tipo de campo de archivo y un atributo enctype con un valor multipart/form-data.

HTML

<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
    <input type="file" name="uploaded_file">
    <input type="submit" name="submit" value="send">
</form>

El campo con name="MAX_FILE_SIZE" se debe colocar sobre input type="file", el valor se establece en bytes. El campo es opcional y la verificación debe estar todavía en el servidor. Después de enviar los datos del archivo cargado, ingrese a la matriz $_FILES

PHP

if(isset($_FILES["uploaded_file"])){ //field´s name type="file"
    $maxsize = 1024 * 1024* 2; //limited the allowed file size to 2 MB
    $errors     = array();
    $acceptable = array( //valid file extensions
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );
 
    if (is_uploaded_file($_FILES['uploaded_file']['tmp_name'])) {
        if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
            $errors[] = 'File too large. File must be less than 2 megabytes.';
        }
        if(!in_array($_FILES['uploaded_file']['type'], $acceptable) && (!empty($_FILES["uploaded_file"]["type"]))){
            $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
        }
        if(!count($errors)) {
            $uploaddir = __DIR__ . '/upload/'; //upload folder
            $uploadfile = $uploaddir . $_FILES['uploaded_file']['name'];
            move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile);
        } else {
            foreach($errors as $error) {
                echo $error . '<br />';
            }
        }
    }
}

Puedes subir varios archivos a la vez. PHP admite la capacidad de transferir una matriz de HTML, incluidos los archivos.

HTML

<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
    <input type="file" name="pictures[]">
    <input type="file" name="pictures[]">
    <input type="file" name="pictures[]">
    <input type="submit" name="submit" value="send">
</form>

PHP

if(isset($_FILES["pictures"])){
   $maxsize = 1024 * 1024* 2;
   $errors     = array();
   $acceptable = array(
       'application/pdf',
       'image/jpeg',
       'image/jpg',
       'image/gif',
       'image/png'
   );
 
   foreach ($_FILES["pictures"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
             if (is_uploaded_file($_FILES['pictures']['tmp_name'][$key])) {
               if(($_FILES['pictures']['size'][$key] >= $maxsize) || ($_FILES["pictures"]["size"][$key] == 0)) {
                   $errors[] = 'File too large. File must be less than 2 megabytes.';
               }
               if(!in_array($_FILES['pictures']['type'][$key], $acceptable) && (!empty($_FILES["pictures"]["type"][$key]))){
                   $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
               }
               if(!count($errors)) {
                   $uploaddir = __DIR__ . '/upload/'; 
                   $uploadfile = $uploaddir . $_FILES['pictures']['name'][$key];
                   move_uploaded_file($_FILES['pictures']['tmp_name'][$key], $uploadfile);
               } else {
                   foreach($errors as $error) {
                       echo $error . '<br />';
                   }
               }
            
            }
        }
    }
}
blog comments powered by Disqus