php - 如何强制下载文件?

新手上路,请多包涵

我想在我的一个网站上的每个视频下方添加一个“下载此文件”功能。我需要强制用户下载文件,而不是仅仅链接到它,因为有时会开始在浏览器中播放文件。问题是,视频文件存储在单独的服务器上。

我可以用 PHP 强制下载吗?

原文由 user15063 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 343
2 个回答

你可以尝试这样的事情:

 <?php

// Locate.
$file_name = 'file.avi';
$file_url = 'http://www.myremoteserver.com/' . $file_name;

// Configure.
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");

// Actual download.
readfile($file_url);

// Finally, just to be sure that remaining script does not output anything.
exit;

我刚刚测试了它,它对我有用。

请注意,要使 readfile 能够读取远程 url,您需要启用 fopen_wrappers

原文由 Paolo Bergantino 发布,翻译遵循 CC BY-SA 4.0 许可协议

测试download.php文件是

function _Download($f_location, $f_name){
  $file = uniqid() . '.pdf';

  file_put_contents($file,file_get_contents($f_location));

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Length: ' . filesize($file));
  header('Content-Disposition: attachment; filename=' . basename($f_name));

  readfile($file);
}

_Download($_GET['file'], "file.pdf");

下载链接是

<a href="download.php?file=http://url/file.pdf"> Descargar </a>

原文由 Elminson De Oleo Baez 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏