php实现点击下载
PHP 实现文件下载
在 PHP 中实现文件下载功能通常需要设置正确的 HTTP 头信息,确保浏览器正确处理文件下载请求。以下是几种常见的实现方式:
使用 header() 函数强制下载
通过设置 Content-Disposition 头信息,强制浏览器弹出下载对话框:
$file_path = '/path/to/file.pdf';
$file_name = 'document.pdf';
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_name) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
}
动态生成文件并下载
对于动态生成的内容(如 CSV 或 PDF),可以直接输出内容并设置下载头信息:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Email', 'Phone']);
fputcsv($output, ['John Doe', 'john@example.com', '123456789']);
fclose($output);
exit;
大文件分块下载
对于大文件,可以使用分块读取方式避免内存问题:
$file_path = '/path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
if (file_exists($file_path)) {
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;
}
安全注意事项
确保文件路径经过验证,防止目录遍历攻击:
$requested_file = basename($_GET['file']);
$safe_directory = '/safe/download/directory/';
$file_path = $safe_directory . $requested_file;
if (!file_exists($file_path) || !is_file($file_path)) {
die('File not found');
}
处理中文文件名
对于包含非ASCII字符的文件名,需要进行编码处理:

$file_name = '中文文件.txt';
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($file_name));
这些方法涵盖了从简单文件下载到更复杂场景的实现,可以根据具体需求选择适合的方式。






