PHP

在PHP中如何实现文件下载响应

小樊
81
2024-08-19 11:03:41
栏目: 编程语言

在PHP中实现文件下载的响应可以通过以下步骤实现:

  1. 使用header()函数设置响应头,包括Content-Type和Content-Disposition。
<?php
$file = 'path/to/your/file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
  1. 使用readfile()函数将文件内容输出到响应流中。
readfile($file);
  1. 完整的示例代码如下:
<?php
$file = 'path/to/your/file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);

通过上述步骤,用户访问该PHP页面时将会触发文件下载,而不是在浏览器中打开文件。

0
看了该问题的人还看了