php - 如何强制下载文件?
我希望在我的网站上的每个视频下方添加“下载此文件”功能。 我需要强制用户下载文件,而不仅仅是链接到它,因为有时会开始在浏览器中播放文件。 问题是,视频文件存储在单独的服务器上。
有什么办法可以强制 PHP 下载吗?
I'm looking to add a "Download this File" function below every video on one of my sites. I need to force the user to download the file, instead of just linking to it, since that begins playing a file in the browser sometimes. The problem is, the video files are stored on a separate server.
Any way I can force the download in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你可以尝试这样的事情:
我刚刚测试过它,它对我有用。
请注意,要使
readfile
能够读取远程 URL,您需要拥有fopen_wrappers
已启用。You could try something like this:
I just tested it and it works for me.
Please note that for
readfile
to be able to read a remote url, you need to have yourfopen_wrappers
enabled.测试过的download.php文件是
,下载链接是
Tested download.php file is
and the link to download is
试试这个:
关键是
header()
。 您需要随下载一起发送标头,它将强制用户浏览器中显示“保存文件”对话框。Try this:
The key is the
header()
. You need to send the header along with the download and it will force the "Save File" dialog in the user's browser.我不知道这是否是最好的方法,但我喜欢这样,简短且简单。 简单的。
如果您想在访问URL时下载文件,您可以执行以下操作
I don't know this is the best way or not but I like that, short & simple.
If you want to download file when you visit URL, you can do like below
index.php
.htaccess
下载.php
index.php
.htaccess
download.php
使用此代码。 是否可以将文件名保存为您想要的名称。 例如,您有 url: http://remoteserver.com/file.mp3 而不是“file.mp3” mp3” 您可以使用此脚本将文件下载为“newname.mp3”
using this code. is it possible to save the file name to what you want. for example you have url: http://remoteserver.com/file.mp3 instead of "file.mp3" can you use this script to download the file as "newname.mp3"