Home » Php » php – How to test if a user has SELECTED a file to upload?

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

Posted by: admin April 23, 2020 Leave a comment


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.


How to&Answers:

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.


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

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

In your case you need code like

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


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.


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


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']))


if ($_FILES['logo']['error'] === 0)

is the only right way