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

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.

Solution 2:

There is a section in php documentation about file handling. You will find that you can check various errors and one of them is

UPLOAD_ERR_OK
    Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
    Value: 4; No file was uploaded.

In your case you need code like

if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }

or

if ($_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { ... }

You should consider checking (and probably providing appropriate response for a user) for other various errors as well.

Solution 3:

You should use is_uploaded_file($_FILES['logo']['tmp_name']) to make sure that the file was indeed uploaded through a POST.

Solution 4:

I would test if (file_exists($_FILES['logo']['tmp_name'])) and see if it works.

Or, more approperately (thanks Baloo): if (is_uploaded_file($_FILES['logo']['tmp_name']))

Solution 5:

We Could Use

For Single file:

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

For Multiple files:

if ($_FILES['logo']['tmp_name'][0] == "") {
    // No files were selected for upload, your (re)action goes here
}