php - 使用 PHP 按扩展类型强制下载文件
问题描述
我试图在单击 url 时自动下载两个文件。我在这篇文章中找到了解决方案How to force file download with PHP and using this code<?php header("Location: http://example.com/go.exe"); ?>
我的目标是按扩展名类型下载 2 个文件,而不是拥有完整的文件名 url,因为文件名将每 1-2 天更改一次,但扩展名将始终保持不变。文件扩展名为 .xls 和 .pdf。我查看了这篇文章 -如何强制下载不同类型的扩展文件 php但没有看到我正在寻找的实际代码。任何指导表示赞赏。谢谢你。
解决方案
你需要解决两个问题:
找到正确的文件。您可以根据自己的需要以不同的方式执行此操作。请参阅此链接:从 php 中某些扩展名过滤的目录中获取文件的最佳方法
// Returns one file from a folder with a specific extension // order is not guaranteed // locate_the_file_by_extension("/my/secret/folder/", "pdf") // folder/file must be readable by php function locate_the_file_by_extension($folder, $extension) { $files = glob($folder."*".$extension); if (count($files)>0) { return $files[0]; } else { throw new Exception("no files found"); } }
下载文件:
// locate_the_file_by_extension('pdf') returns the file you want to download $filename = locate_the_file_by_extension(); $size = filesize($filename); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: binary'); header('Connection: Keep-Alive'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $size); // read the file echo file_get_contents($filename);
确保没有其他内容发送到输出。额外的输出会损坏文件或标题。
推荐阅读
- javascript - Vuejs中不显示密码字段的验证错误消息?
- python - 如何在 Python 的同一公式中使用列表列表的元素?
- python - 如何从 DataFrame 中删除多个索引?
- python - 使用 python 脚本创建 SQLite 中的列时未显示数据类型
- jenkins - 具有 ebextensions 的 NodeJS 应用程序未通过 Jenkins 作业部署到 Beanstalk
- javascript - javascript OR 操作似乎不适用于前两个选项
- php - 未定义索引:App\LoginToken {"userId":3,"exception":"[object] Laravel 8
- javascript - 如何从另一个窗口触发调整大小事件的窗口?
- typescript - 在 Typescript 中使用自定义键展平对象
- amazon-web-services - 在 AWS 托管服务中将域与登录页面和 Web 应用程序分开