[英]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.