php实现app下载
实现 PHP 下载功能
在 PHP 中实现文件下载功能通常通过设置 HTTP 头信息并输出文件内容来完成。以下是实现的基本方法:
设置正确的 HTTP 头信息
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
读取并输出文件内容
readfile($file);
exit;
完整下载函数示例
function downloadFile($file) {
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
die('文件不存在');
}
}
处理大文件下载
对于大文件下载,可以使用分块读取的方式减轻内存压力:
$chunkSize = 1024 * 1024; // 1MB chunks
$handle = fopen($file, 'rb');
while (!feof($handle)) {
$buffer = fread($handle, $chunkSize);
echo $buffer;
ob_flush();
flush();
}
fclose($handle);
安全注意事项
验证用户权限 在提供下载前应验证用户是否有权限下载该文件。
防止目录遍历攻击
$basePath = '/safe/download/directory/';
$realBase = realpath($basePath);
$userPath = $basePath . $_GET['file'];
$realUserPath = realpath($userPath);
if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) {
die('非法文件路径');
}
设置下载限速
$downloadRate = 100; // 100KB/s
while (!feof($handle)) {
$buffer = fread($handle, $downloadRate * 1024);
echo $buffer;
ob_flush();
flush();
sleep(1);
}






