[英]Managing php sessions on multiple file uploads
我正在使用多张图片上传社交网络应用程序。 我为每个上传的文件分配一个$_session['file_id']
作为数组索引(文件ID来自db)。 但我只希望用户每个帖子最多上传4张图片。 因此,我在上载之前先计算images.length
,如果== 4
,则警告用户他不能同时上传更多文件,否则会发生正常的上传。 为了安全起见,我有一个unset($_session['file_id'])
来确保不会因错误而上传这4个文件,或者确保用户不会在javascript上进行更改(每次上载都进行for
循环),以计算$_session['file_id'])
。 我遇到的问题是js本身不足以确保文件没有上传4次,我猜ajax上传仍在队列中,并在上传第4个文件之前检查文件号。 还有什么其他方法可以直接在php上使用,请记住我无法为普通用户取消设置文件(4个文件已经上传并等待发送按钮),但是如果用户刷新或退出页面,我需要加取消设置文件? 感谢您的宝贵时间。
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)
}
})
并在#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");
}
}
}
为<input>
分配一个随机的类名,例如:
<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>
初始化之后, $('.fileuploadCounter').length()
将返回该类的元素数量,在本示例中为4。 请参阅jQuery文档 。
将<input>
标记上的名称更改为images[]
,并计数$_POST['images']
服务器端。
例如:
<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"]); } } } } ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.