我想在我的某个网站上的每个视频下面添加“下载此文件”功能。我需要强制用户下载文件,而不是仅仅链接到文件,因为有时候开始在浏览器中播放文件。问题是,视频文件存储在单独的服务器上。
我可以用PHP强制下载吗?
答案 0 :(得分:39)
您可以尝试这样的事情:
$file_name = 'file.avi';
$file_url = 'http://www.myremoteserver.com/' . $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_url);
exit;
我刚试过它,它对我有用。
请注意,要让readfile
能够阅读远程网址,您需要启用fopen_wrappers
。
答案 1 :(得分:5)
经过测试的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>
答案 2 :(得分:2)
试试这个:
<?php
$FileName = '/var/ww/file.txt';
header('Content-disposition: attachment; filename="'.$FileName.'"');
readfile($FileName);
关键是header()
。您需要将标题与下载一起发送,它将强制在用户的浏览器中显示“保存文件”对话框。
答案 3 :(得分:0)
<?php
$FileName = '/var/ww/file.txt';
header('Content-disposition: attachment; filename="'.$FileName.'"');
readfile($FileName);
使用此代码。是否可以将文件名保存到您想要的位置。例如你有url:http://remoteserver.com/file.mp3而不是“file.mp3”你可以使用这个脚本将文件下载为“newname.mp3”
答案 4 :(得分:0)
thread
答案 5 :(得分:0)
我不知道这是否是最好的方法,但我喜欢这样,简短而简单。
如果您要在访问 URL 时下载文件,可以按以下步骤操作
<a href="resume.pdf" download></a>
<script>document.querySelector('a').click();</script>
答案 6 :(得分:0)
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>download</title>
</head>
<body>
<a href="download.php?file=ID_do_arquivo"> download </a>
</body>
</html>
.htaccess
Options -Indexes
Options +FollowSymlinks
deny from all
download.php
$file = "pdf/teste.pdf";
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit();
}