Search code examples
phpfileupload

How to test if a user has SELECTED a file to upload?


on a page, i have :

if (!empty($_FILES['logo']['name'])) {
    $dossier     = 'upload/';
    $fichier     = basename($_FILES['logo']['name']);
    $taille_maxi = 100000;
    $taille      = filesize($_FILES['logo']['tmp_name']);
    $extensions  = array('.png', '.jpg', '.jpeg');
    $extension   = strrchr($_FILES['logo']['name'], '.');

    if(!in_array($extension, $extensions)) {
        $erreur = 'ERROR you  must upload the right type';
    }

    if($taille>$taille_maxi) {
         $erreur = 'too heavy';
    }

    if(!empty($erreur)) {
      // ...
    }
}

The problem is, if the users wants to edit information WITHOUT uploading a LOGO, it raises an error : 'error you must upload the right type'

So, if a user didn't put anything in the inputbox in order to upload it, i don't want to enter in these conditions test.

i tested : if (!empty($_FILES['logo']['name']) and if (isset($_FILES['logo']['name'])

but both doesn't seems to work.

Any ideas?

edit : maybe i wasn't so clear, i don't want to test if he uploaded a logo, i want to test IF he selected a file to upload, because right now, if he doesn't select a file to upload, php raises an error telling he must upload with the right format.

thanks.


Solution

  • You can check this with:

    if (empty($_FILES['logo']['name'])) {
        // No file was selected for upload, your (re)action goes here
    }
    

    Or you can use a javascript construction that only enables the upload/submit button whenever the upload field has a value other then an empty string ("") to avoid submission of the form with no upload at all.