Download remote file with curl directly

I want to download a remote file with curl and send it to the user right away. The user should think that he is downloading the file from my server instead of the remote server. I cannot buffer all files because some files are larger than 200 MB. Also, the user will have to wait for the completion of buffering until he begins to download the file.

I found a script to download a file from a remote server directly:

<?php $file_name = $_GET['file']; $file_url = 'http://www.remote.tld/' . $file_name; header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"".$file_name."\""); readfile($file_url); exit; ?> 

Is such direct remote downloading possible with curl?

+4
source share
2 answers

You will need to read and display the file in chunks, as the entire 200MB file will probably not fit in your PHP script memory.

See this question on how to do this in curl. The manual provides an example. Stolen and changed from this, something like this should work (unchecked):

 <?php curl_setopt($this->curl_handle, CURLOPT_WRITEFUNCTION, "receiveResponse"); function receiveResponse($curlHandle,$data) { echo $data; // Ouput to the user $length = strlen($data); return $length; } ?> 

Note that this is rarely a good idea. This puts a relatively large load on the server - if you have high enough traffic numbers, this is a high price to pay for the vanity of serving the download. Also, of course, a 200 MB download will create 400 MB of your traffic bill!

+5
source

You cannot serve a file from your server without buffering it on your server.

There is no technical solution, also not with CURL, since you do not have access to the DNS server of the opposite server to hide the opposite URL.

0
source

Source: https://habr.com/ru/post/1339195/


All Articles