How to interact with inputs type file?

2

When I have a form with an input of type file when sending it, in my receiving action as I can check if it is set or not as with

if (isset($_POST['my_file'])){ echo "bla"; }

does not work

<form enctype="multipart/form-data" id="my_form" action="<?php echo $yomismo; ?>" method="post">
  <input type="file" name="my_file">
 </form>
    
asked by Pavlo B. 02.01.2017 в 18:30
source

3 answers

2

You have to change the global variable $_POST to $_FILES .

Then to check if the file has been uploaded successfully you can check it like this:

$phpFileUploadErrors = [
    0 => 'No hay error, el archivo se ha subido con éxito',
    1 => 'El archivo subido supera la directiva upload_max_filesize en php.ini',
    2 => 'El archivo subido supera la directiva MAX_FILE_SIZE que se especificó en el formulario HTML',
    3 => 'El archivo subido sólo se cargó parcialmente',
    4 => 'No se ha cargado ningún archivo',
    6 => 'Falta una carpeta temporal',
    7 => 'Error al escribir el archivo en el disco',
    8 => 'Una extensión de PHP detuvo la subida del archivo',
];

if ($_FILES['my_file']['error'] === UPLOAD_ERR_OK) {

    // El archivo se ha cargado con éxito

}
else {

    // Hubo un error
    echo $phpFileUploadErrors[$_FILES['my_file']['error']];
}

+ Info about possible errors

    
answered by 02.01.2017 / 18:53
source
2

It is verified in this way:

 if( isset($_FILES['my_file']) && count($_FILES['my_file']['error']) == 1 && $_FILES['my_file']['error'][0] > 0)
{
     //file no seleccionado
}
else if(isset($_FILES['my_file']))
{
     echo "blah seleccionado";
}

See more extended examples here .

    
answered by 02.01.2017 в 18:38
1

Try checking if the file size is greater than 0, you can do it in the following way:

...
if ($_FILES['my_file']['size'] > 0) { 
   echo "bla";
}
...
    
answered by 02.01.2017 в 18:59