php怎么实现下载文件
实现文件下载的基本方法
在PHP中实现文件下载可以通过设置HTTP头信息强制浏览器下载文件而非直接显示。以下是基本实现方式:
$file_path = '/path/to/your/file.ext';
$file_name = 'download_name.ext';
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;
}
处理大文件下载
对于大文件下载,为避免内存问题,可以使用分块读取的方式:

$chunk_size = 1024 * 1024; // 1MB chunks
$handle = fopen($file_path, 'rb');
while(!feof($handle)){
$buffer = fread($handle, $chunk_size);
echo $buffer;
ob_flush();
flush();
}
fclose($handle);
安全下载实现
为防止目录遍历攻击,应对文件路径进行验证:

$base_dir = '/safe/download/directory/';
$requested_file = $_GET['file'];
$real_path = realpath($base_dir . $requested_file);
if($real_path && strpos($real_path, $base_dir) === 0 && is_file($real_path)){
// 安全下载代码
} else {
die('Invalid file');
}
断点续传支持
实现断点续传需要处理HTTP_RANGE头:
$size = filesize($file_path);
$start = 0;
$end = $size - 1;
if(isset($_SERVER['HTTP_RANGE'])){
$range = $_SERVER['HTTP_RANGE'];
$range = str_replace('bytes=', '', $range);
list($start, $end) = explode('-', $range);
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes '.$start.'-'.$end.'/'.$size);
} else {
header('HTTP/1.1 200 OK');
}
header('Accept-Ranges: bytes');
header('Content-Length: '.($end - $start + 1));
常见MIME类型设置
根据文件类型设置正确的Content-Type:
$mime_types = [
'txt' => 'text/plain',
'pdf' => 'application/pdf',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'zip' => 'application/zip'
];
$ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
if(array_key_exists($ext, $mime_types)){
header('Content-Type: '.$mime_types[$ext]);
} else {
header('Content-Type: application/octet-stream');
}






