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
Since
user_attachment[]
is an array you can easily check with thecount()
function.You can check by using the
size
field on the$_FILES
array like so:(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