可以使用以下代码来实现 PHP 下载文件功能:
$file = "example.pdf"; // 文件名
$filepath = "/path/to/file/" . $file; // 文件路径
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . $file);
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($filepath));
readfile($filepath);
在上述代码中,我们首先定义了要下载的文件名和文件路径,然后设置了响应头信息,使浏览器将文件下载到本地。Content-Type
可以指定下载文件的 MIME 类型,Content-Disposition
中的 attachment
参数告诉浏览器将文件作为附件下载,Content-Transfer-Encoding
指定传输编码方式,并且在头信息中设置了要下载文件的大小,最后使用 readfile
函数将文件内容输出到浏览器,从而完成文件下载操作。