php实现pdf下载
PHP实现PDF下载的方法
使用PHP实现PDF文件下载可以通过设置HTTP头信息来控制浏览器的行为,强制触发下载而非直接打开文件。以下是几种常见方法:
使用header()函数强制下载
设置正确的HTTP头信息,指定内容类型为PDF并添加附件下载提示:
$filePath = '/path/to/your/file.pdf';
$fileName = 'document.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
从URL生成PDF并下载
若需动态生成PDF内容(如使用TCPDF、FPDF等库):

require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
$pdf->Write(0, 'Sample PDF Content');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="generated.pdf"');
echo $pdf->Output('', 'S');
处理远程PDF下载
从远程服务器获取PDF并转发给客户端:
$remoteUrl = 'https://example.com/document.pdf';
$pdfContent = file_get_contents($remoteUrl);
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
echo $pdfContent;
添加缓存控制
对于大文件或需要防止重复下载的情况:

header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Expires: 0');
安全注意事项
-
验证文件路径防止目录遍历攻击:
$baseDir = '/safe/directory/'; $userFile = $_GET['file']; if (strpos(realpath($baseDir . $userFile), $baseDir) !== 0) { die('Invalid file path'); } -
对大文件使用分块读取避免内存溢出:
$chunkSize = 1024 * 1024; $handle = fopen($filePath, 'rb'); while (!feof($handle)) { echo fread($handle, $chunkSize); ob_flush(); flush(); } fclose($handle);






