Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 located) 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?

like image 203
DiglettPotato Avatar asked Oct 29 '10 18:10

DiglettPotato


People also ask

How can download file from server to local machine in PHP?

You can download any type of file (image, ZIP, video, audio, etc) from the remote server using PHP. Use the readfile() function with application/x-file-to-save Content-type header, to download a ZIP file from remote URL using PHP. header("Content-type: application/x-file-to-save");

What is a PHP proxy?

Proxy is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object.


2 Answers

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.

like image 182
Byron Whitlock Avatar answered Oct 02 '22 03:10

Byron Whitlock


        $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.

like image 38
Robert Trzebiński Avatar answered Oct 02 '22 01:10

Robert Trzebiński