Reputation: 6054
I'm working in a multiple image upload social web app. I'm assigning a $_session['file_id']
to each uploaded file as an array index (file id comes from db). But I only want users to upload a maximum of 4 images per post. So I'm counting the images.length
before upload, and if it's == 4
, alerting the user he can't upload more files at the same time, else, the normal upload happens. For security purposes I have an unset($_session['file_id'])
for making sure the 4 files won't be uploaded on errors, or user changes on javascript (a for
loop on every upload, to count $_session['file_id'])
.
The problem I'm having is that the js itself ain't enought to make sure the file ain't uploaded 4 times, I guess ajax upload stay on queue, and check for file number before the 4th file is uploaded. Is there any other approach I can use direct on php, remembering I can't unset files for common users (4 files are already upload and waiting for send button), but I need plus to unset files if user reflesh, or quit the page? Thank your for your time.
JavaScript
var checkfilecount = 0;
$('#file').change(function() {
checkfilecount++;
checkfile = $("#images).length;
if (checkfile < 4 && checkfilecount < 4) {
$("#filesend").submit();
}
else {
setTimeout(function(){
alert("Sorry, You can`t upload too many files at once")
},3000)
}
})
and on #postsend:
checkfilecount = 0;
PHP
if (isset($_SESSION['files_id'])) {
$counting = 0;
foreach($_SESSION['files_id'] as $key => $val)
{
$counting++;
if ($counting == 4) {
unset($_SESSION['files_id']);
exit("error on session array");
}
}
}
Upvotes: 0
Views: 1101
Reputation: 15959
Assign a random classname to the <input>
s for example:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" class="fileuploadCounter">
<input type="file" name="file[]" class="fileuploadCounter">
<input type="file" name="file[]" class="fileuploadCounter">
<input type="file" name="file[]" class="fileuploadCounter">
</form>
After init, $('.fileuploadCounter').length()
will return the amount of elements with that class, in this example, four. See the jQuery documentation.
Change the name on the <input>
tags to images[]
, and count $_POST['images']
server side.
Eg:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(isset($_FILES['file'])){
// Because we added [] in the name tag and they match names, $_FILES['file'] is now an array containing the images.
if(count($_FILES['file']) > 4){
// More than 4 files
}
else
{
// Less then four!
foreach($_FILES['file'] as $file){
move_uploaded_file($file["file"]["tmp_name"], "uploads/" . $files["file"]["name"]);
}
}
}
}
?>
Upvotes: 1