php下载进度实现
PHP 下载进度实现
要实现 PHP 下载进度功能,可以通过以下方法监控和显示下载进度。以下是几种常见的实现方式:
使用 curl 扩展监控进度
PHP 的 curl 扩展支持进度回调函数,可以实时获取下载进度信息。
$url = 'http://example.com/largefile.zip';
$file = 'downloaded.zip';
$fp = fopen($file, 'w+');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($resource, $download_size, $downloaded, $upload_size, $uploaded) {
if ($download_size > 0) {
$progress = round(($downloaded / $download_size) * 100, 2);
echo "Download Progress: {$progress}%\n";
}
});
curl_exec($ch);
curl_close($ch);
fclose($fp);
使用 file_get_contents 分块下载
对于不支持 curl 的环境,可以通过分块下载并计算进度。
$url = 'http://example.com/largefile.zip';
$file = 'downloaded.zip';
$chunk_size = 1024; // 1KB per chunk
$context = stream_context_create([], ['notification' => function($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
if ($notification_code == STREAM_NOTIFY_PROGRESS && $bytes_max > 0) {
$progress = round(($bytes_transferred / $bytes_max) * 100, 2);
echo "Download Progress: {$progress}%\n";
}
}]);
$data = file_get_contents($url, false, $context);
file_put_contents($file, $data);
前端实时显示进度
结合前端技术(如 AJAX 或 WebSocket),可以将进度实时显示在网页上。
后端 PHP (progress.php):
session_start();
$progress = $_SESSION['download_progress'] ?? 0;
echo json_encode(['progress' => $progress]);
前端 JavaScript:

function checkProgress() {
fetch('progress.php')
.then(response => response.json())
.then(data => {
console.log(`Progress: ${data.progress}%`);
if (data.progress < 100) {
setTimeout(checkProgress, 1000);
}
});
}
checkProgress();
注意事项
- 确保服务器支持大文件下载,并配置适当的
php.ini参数(如memory_limit和max_execution_time)。 - 分块下载时需处理网络中断和重试逻辑。
- 对于敏感文件,需验证下载权限以避免未授权访问。
通过以上方法,可以灵活实现 PHP 下载进度功能,并根据实际需求调整实现方式。






