我有以下download.php
脚本来下载一个文件,效果很好:
<?php
header("Content-Type: application/octet-stream");
$file = $_GET["file"];
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush();
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
?>
我想要实现的是隐藏这个文件所在的URL,这样当用户单击<a target="_blank" href="http://domain.com/files/download.php?file=filename.pdf">Download file</a>
之类的链接时,就会打开一个没有URL的新选项卡,并开始对文件进行下载。实际情况是,新的选项卡打开,文件下载开始,但URL栏显示http://domain.com/files/download.php?file=filename.pdf
。
如果php无法做到这一点,我该如何实现?我看过几次没有显示URL的下载,所以我知道这在某种程度上是可能的。
编辑:我想这样做的原因是:我们将发送一封带有文件下载链接的html邮件,而托管该文件下载的网站不是发送邮件的公司的网站。
一如既往,非常感谢。
一种典型的方法是将要提供下载的文件放置在docroot之外。您的下载脚本应该知道这个地方,并且必须考虑到这一点来处理请求的文件名。
例如:
path/in/your/system/docroot/download.php
和path/in/your/system/files/filename.pdf
如果有人请求download.php?file=filename.pdf
,您的脚本必须在path/in/your/system/files/
中查找该文件并进行处理。
您可以创建一个新窗口,其中包含该URL的iframe内容。
var win = window.open("", "Title", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=780, height=200, top="+(screen.height-400)+", left="+(screen.width-840));
win.document.body.innerHTML = "<iframe src='YOUR URL'></iframe>";
如果删除target="_blank"
,则不会打开新的选项卡,只会下载文件。
最终,这是不可能的,因为用户可以打开谷歌检查器并检查网络选项卡。
编辑:如果是这样的话,你会使用JavaScript:
编辑2:如果弹出窗口被浏览器或插件阻止,请使用回退:
编辑3:如果JS被禁用:
<head><meta http-equiv="refresh" content="5;http://domain.com/files/download.php?file=filename.pdf">
<script>
var win = window.open("http://domain.com/files/download.php?file=filename.pdf");
if (!win) {
window.location = "http://domain.com/files/download.php?file=filename.pdf";
}
</script>
</head>
编辑4:如果你根本不想让用户看到用户网站的域,让你的PHP脚本下载文件,然后输出给用户:
header("Content-Type: application/octet-stream");
$file = $_GET["file"];
$file = 'http://otherdomain.com/location/' . $file; // This line should suffice for all that you're trying to do
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush();
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
以POST形式提交表单,并使用$_REQUEST获取文件:
$file = $_REQUEST["file"];