skip to Main Content

I send the data from a form with jquery ajax to php file.
I want to check if a user has chosen at least 1 file.
This is part of my form for the attachment file:

<input type="file" class="form-control-file" name="user_attachment[]" multiple="multiple">

My jquery ajax:

$.ajax({
    url: "contact.php",
    type: "POST",
    data:  new FormData(this),
    contentType: false,
    cache: false,
    processData:false,
    success: function(data){
        $(".response").html(data);
        $('.spinner').hide();
    },
                
});

And to check in contact.php if no file has been chosen:

$user_attachment_tmp = $_FILES['user_attachment']['tmp_name'];
$user_attachment = $_FILES['user_attachment']['name'];

// several checks if no file is chosen
if( empty($_FILES['user_attachment']['name']) ) {
    echo 'no file chosen'; // fails when nothing is chosen
}

if(!isset($_FILES['user_attachment']) || $_FILES['user_attachment']['error'] == UPLOAD_ERR_NO_FILE) {
    echo 'no file chosen'; // fails when nothing is chosen
}

if(!file_exists($_FILES['user_attachment']['tmp_name']) || !is_uploaded_file($_FILES['user_attachment']['tmp_name'])) {
    echo 'no file chosen'; // fails when nothing is chosen
}

So the problem is: in each case, when no file is selected, i do NOT get the message no file chosen

So how can i check if no file is selected (attached in the form)?

2

Answers


  1. Since user_attachment[] is an array you can easily check with the count() function.

    $count = count($_FILES['user_attachment']['name']);
    for ($i = 0; $i < $count; $i++) {
        if (empty($_FILES['user_attachment']['name'][$i])) {
            echo 'no file chosen';
        }
    
        if ($_FILES['user_attachment']['error'][$i] == UPLOAD_ERR_NO_FILE) {
            echo 'no file chosen';
        }
    
        if (!file_exists($_FILES['user_attachment']['tmp_name'][$i]) || !is_uploaded_file($_FILES['user_attachment']['tmp_name'][$i])) {
            echo 'no file chosen';
        }
    }
    
    Login or Signup to reply.
  2. You can check by using the size field on the $_FILES array like so:

    if ($_FILES['user_attachment']['size'] == 0 && $_FILES['user_attachment']['error'] == 0)
    {
        // user_attachment is empty (and not an error)
    }
    

    (I also check error here because it may be 0 if something went wrong. I wouldn’t use name for this check since that can be overridden)

    Copied from Rudi Visser answer

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search