How do I use my server as a proxy to download files via PHP?
I need my server to act as a proxy between a 3rd party server (where the file is originally locate开发者_如何学God) and the end user. That is, my server downloads the file from the 3rd party server, and sequentially, the user downloads it from my server. This should result in an incurred bandwidth of twice the file size. How can this process be achieved using PHP?
Very very simply like this:
$url = $_GET['file'];
$path_parts = pathinfo($url);
$ext = $path_parts['extension'];
$filename = $path_parts['filename'];
header("Content-type: application/$ext");
header("Content-Disposition: attachment; filename=$filename");
echo file_get_contents($url);
If the file is larger than a few megabytes, use fopen fread and frwrite download the file in chunks and send to the client in chunks.
$fp = fopen($url, 'rb');
foreach (get_headers($url) as $header)
{
header($header);
}
fpassthru($fp);
exit;
This will simply download a remote file to the browser with correct headers.
file_get_contents()
will not load the page until the entire file is downloaded to memory
readfile()
will show the page right away yet continue downloading the file in memory, streaming it to the client
Example usage using an EXE:
$url = "https://path/to/file.exe";
$filename = "SaveAsFile.exe
header("Content-Disposition: attachment; filename=$filename");
readfile($url);
精彩评论