Search code examples
phpfilehttp-headersmime-typesbandwidth

How can I use php headers to download an external file without using bandwidth on my server?


I've been using SO for a long time but finally had a question I couldn't find an answer for. I want to use my site to redirect a user to a file that is hosted on another server. At first I thought "this should be easy":

header("Location: $url")

However, the file hosted on the other server just has a uuid as a filename, so I want to use headers to pass an appropriate mimetype and filename (which I will know). This I can do with the following code:

<?php
$filename = $_REQUEST["name"];
$filesize = $_REQUEST["size"];
$mimetype = $_REQUEST["mime"];
$url = $_REQUEST["url"];

// used to test
$filename = "example.txt";
$filesize = "2966";
$mimetype = "text/plain";
$url = "http://example.com";

header('Content-Type: ' . $mimetype); 
header("Content-length: " . ($filesize + 0)); 
header('Content-Disposition: attachment; filename="' . $filename . '"'); 

// this just redirects to the page, ignoring the Content- headers
//header('Location: ' . $url);

// this works, but I suspect that it uses my server's bandwidth
readfile($url);
exit();

?>

The method I've posted above does indeed present the user with a download, but doesn't it pass the download through my own servers? I could potentially be downloading a lot of files with this and I'd rather not use my own bandwidth for this if I don't have to. I realize this may not be possible, but I appreciate any insight.


Solution

  • The short answer is, this just isn't possible; a browser will only look at the headers from the server delivering the file.

    You either need to proxy the request via your server (which without caching doubles the bandwidth), or talk to the owner of the site files are downloaded from about supporting your requirements.