大檔案上傳若無進度回饋,使用者易因等待焦慮而中斷操作。PHP 5.4+ 內建 session.upload_progress 機制,無需額外擴展即可實現即時進度顯示。本文從原理到完整前後端實作,打造流暢的上傳體驗。
<input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" value="upload_123">(名稱由 session.upload_progress.name 決定)。$_SESSION['upload_progress_upload_123']。; 必須啟用
session.upload_progress.enabled = On
session.upload_progress.cleanup = On
session.upload_progress.prefix = "upload_progress_"
session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
session.upload_progress.freq = "1%"
session.upload_progress.min_freq = "1"
; 確保 session 可寫入、檔案上傳限制足夠
post_max_size = 100M
upload_max_filesize = 100M
max_execution_time = 300
max_input_time = 300
<?php
session_start();
$progressKey = ini_get('session.upload_progress.prefix') . $_POST['progress_key'] ?? '';
if (isset($_GET['progress'])) {
// 進度查詢端點
header('Content-Type: application/json');
if (isset($_SESSION[$progressKey])) {
$data = $_SESSION[$progressKey];
$progress = $data['content_length'] > 0
? round($data['bytes_processed'] / $data['content_length'] * 100, 2)
: 0;
echo json_encode(['progress' => $progress, 'bytes' => $data['bytes_processed'], 'total' => $data['content_length']]);
} else {
echo json_encode(['progress' => 0, 'bytes' => 0, 'total' => 0]);
}
exit;
}
// 檔案上傳處理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$targetDir = __DIR__ . '/uploads/';
$fileName = basename($_FILES['file']['name']);
$targetPath = $targetDir . uniqid() . '_' . $fileName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
echo json_encode(['success' => true, 'path' => $targetPath]);
} else {
http_response_code(500);
echo json_encode(['success' => false, 'error' => '移動檔案失敗']);
}
exit;
}
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>上傳進度示範</title>
<style>
.progress-bar {width: 100%; height: 24px; background: #eee; border-radius: 4px; overflow: hidden;}
.progress-fill {height: 100%; background: #4caf50; width: 0%; transition: width 0.3s;}
</style></head><body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" value="demo_upload">
<input type="file" name="file" id="fileInput" required><br><br>
<button type="submit">開始上傳</button>
</form>
<div class="progress-bar" style="margin-top:16px; display:none;" id="progressBar">
<div class="progress-fill" id="progressFill"></div>
</div>
<div id="status"></div>
<script>
const form = document.getElementById('uploadForm');
const progressBar = document.getElementById('progressBar');
const progressFill = document.getElementById('progressFill');
const status = document.getElementById('status');
let pollTimer = null;
form.addEventListener('submit', async (e) => {
e.preventDefault();
const file = document.getElementById('fileInput').files[0];
if (!file) return;
progressBar.style.display = 'block';
progressFill.style.width = '0%';
status.textContent = '上傳中...';
const formData = new FormData(form);
// 開始上傳
const uploadResp = fetch('upload.php', {method: 'POST', body: formData});
// 輪詢進度
pollTimer = setInterval(async () => {
const res = await fetch('upload.php?progress=1&progress_key=demo_upload');
const data = await res.json();
progressFill.style.width = data.progress + '%';
progressFill.textContent = data.progress.toFixed(1) + '%';
if (data.progress >= 100) clearInterval(pollTimer);
}, 500);
try {
const result = await uploadResp;
const data = await result.json();
if (data.success) {
status.textContent = '上傳成功:' + data.path;
} else {
status.textContent = '失敗:' + data.error;
}
} catch (err) {
status.textContent = '錯誤:' + err.message;
} finally {
clearInterval(pollTimer);
}
});
</script>
</body></html>
session.upload_progress.cleanup = On 會在請求結束自動刪除進度資料,輪詢腳本需在同一 Session 域下,且不能在上傳腳本結束前清理。session_write_close() 釋放 Session 鎖,進度更新將停止,避免在上傳腳本中過早呼叫。client_max_body_size 預設 1MB,必須調大。Session Upload Progress 提供了零依賴的原生進度追蹤方案,配合簡單的 AJAX 輪詢即可實現專業級上傳體驗。對於超大檔案或高併發場景,建議升級至分片上傳 + WebSocket 架構。