Php强制浏览器下载文件没有重定向

时间:2015-07-24 06:40:37

标签: php

我在http://domain.com/download.php

上有这段代码
<?php
$remote_direct_link = "http://example.com/path/to/movie.mp4";
$filename = "movie-test.mp4";
$ctype="application/octet-stream";
header("HTTP/1.0 302 Found");
header("Content-Type: ".$ctype);
header("Connection: close");
header("Content-Disposition: attachment;  filename=\"".basename($filename).'"');
header("Location: " . $remote_direct_link);
?>

当我在浏览器上访问domain.com/download.php时,我希望在浏览器上使用对话框强制下载文件movie-test.mp4。但不幸的是,它总是重定向到http://example.com/path/to/movie.mp4并在浏览器上播放。怎么办呢?我的代码有什么问题吗? 感谢

2 个答案:

答案 0 :(得分:1)

首先,从远程目标下载文件然后将其发送到客户端似乎是一个非常糟糕的主意。它提供了大量的开销数据传输。客户端必须等到您下载文件,然后才能提供服务。大文件需要很长时间。此外,如果远程目标无法访问,则会出现新问题。

话虽这么说,你应该传递文件的内容,而不是重定向。

<?php
$remote_direct_link = "http://example.com/path/to/movie.mp4";
$filename = "movie-test.mp4";
$ctype="application/octet-stream";
header("HTTP/1.0 302 Found");
header("Content-Type: ".$ctype);
header("Connection: close");
header("Content-Disposition: attachment;  filename=\"".basename($filename).'"');
echo file_get_contents($remote_direct_link); // instead of redirection
?>

但更好更简单的方法就是在本地使用该文件。它使您能够更快地提供文件,并节省一半的数据传输。

<?php
$file_contents = file_get_contents('../outside_http/movie.mp4');
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"movie-test.mp4\""); 
echo $file_contents;

答案 1 :(得分:0)

代码中的最后一行将用户重定向到外部URL,这会导致忽略所有其他代码。相反,您可能想尝试使用readfile()函数,如;

readfile($remote_direct_link);