使用 PHP 下载文件。如何获取文件名?
我需要使用 PHP 脚本从远程服务器下载文件。问题是我收到的链接看起来像“example.com?download=12345”。因此,我想使用正确的扩展名保存文件,并(最多)保留其原始文件名。我该如何操作? 谢谢大家!
I need to download files from remote server with my PHP script. The problem is that the links I recieve look like "example.com?download=12345". So I want to save the file with correct extension and (at best) preserve it's original filename. How do I do this?
Thank you all!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
HTTP 响应中的
Content-Disposition
标头(如果存在)将包含其他服务器希望该文件具有的文件名。The
Content-Disposition
header in the HTTP response, if it exists, will contain the filename the other server wants the file to have.@EricLaw(IE 团队的)发布了 去年 11 月在 IEBlog 上对此进行了详细分析。虽然他的帖子主要针对 IE,但基本知识适用于大多数浏览器:
但是,源服务器没有义务执行任何此操作;最有可能的选项是
Content-Disposition
标头。如果不存在,您将返回到第 1 步(尽管您可以根据文件内容猜测文件类型)。@EricLaw (of the IE Team) has posted a detailed analysis of this on the IEBlog last November. While his post is focused on IE, the basics hold for most browsers:
However, the source server is not obliged to do any of this; the most likely option would be the
Content-Disposition
header. If that is not present, you are back to square 1 (although you could guesstimate the file type from its content).如果您使用的是curl,响应标头应返回实际的文件名。文件下载的标头如下所示:
If you are using curl, the response header should return the actual filename. The header for file downloads looks like: