php 实现点击下载
实现 PHP 点击下载功能
使用 PHP 实现文件下载功能通常涉及设置正确的 HTTP 头部信息,并输出文件内容。以下是几种常见的实现方法:
基本文件下载
$file_path = 'path/to/your/file.pdf';
$file_name = basename($file_path);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
动态生成内容下载
对于动态生成的内容(如 CSV 数据),可以直接输出:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['Column1', 'Column2']);
fputcsv($output, ['Data1', 'Data2']);
fclose($output);
exit;
大文件分块下载
处理大文件时可以使用分块读取:
$file_path = 'large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
安全注意事项
确保对下载文件路径进行验证,防止目录遍历攻击:
$base_dir = '/safe/download/directory/';
$requested_file = $_GET['file'];
$file_path = realpath($base_dir . $requested_file);
if ($file_path === false || strpos($file_path, $base_dir) !== 0) {
die('Invalid file requested');
}
前端触发下载
HTML 中可以通过链接或表单触发下载:
<a href="download.php?file=document.pdf">Download PDF</a>
<form method="post" action="download.php">
<input type="hidden" name="file" value="report.docx">
<button type="submit">Download Document</button>
</form>





