I'm trying to upload two images in one form using ajax and php. I'm using FormData
to get the form's information, which works fine. This is the HTML:
<form enctype="multipart/form-data">
<input type="file" name="file[]" class="file">
<input type="file" name="file[]" class="file">
<button type="submit">Submit</button>
</form>
and here's the javascript code:
var form = document.querySelector('form');
$("form").on("submit", function(e) {
e.preventDefault();
var formdata = new FormData(form);
$.ajax({
url: 'double_image_upload_response.php',
type: 'POST',
data: formdata,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
});
On the server side in PHP, I'm using this to get the names of the files:
$files = $_FILES['file']['name'];
and this works fine. So, for example, if I had two files, one named "tree.jpg" and the other named "orange.jpg", I would get the names in that form within an array, which is good.
To get the names out of the array, I use a foreach
loop:
foreach($files as $names) {
echo $names;
}
This gives me the values "tree.jpg" and "orange.jpg" outside of the array. However, when I try to check if the extensions are valid, I have trouble. Using this php array containing the valid image extensions:
$allowed = ['image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'];
I then add some code to the inside of the foreach
loop I just showed, resulting in this:
foreach($files as $names) {
if (in_array($names, $allowed)) {
echo "Valid image extension";
} else {
echo "Invalid image extension";
}
}
and it keeps echoing out "Invalid image extension", but I don't know why.
I already tried using the explode()
and end()
functions to get the extension and compare that to the $allowed
array, without luck. I also tried the array_search
function, which didn't work, either. Any ideas?
`