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


Php force browser download file without redirect

我在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并在浏览器上播放。它是如何做到的呢?我的代码有问题吗?由于

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

也就是说,您应该传递文件的内容,而不是重定向。

<?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;

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

readfile($remote_direct_link);