File download with curl and php

Question:

I have two servers, server1 and server2 , server2 only accepts requests from server1 if it is another ip it returns 404, my site is on server1 and the files for download on server2 , I made the following script to return the download from server2 :

    ob_start();
    set_time_limit(0);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $r = curl_exec($ch);
    curl_close($ch);
    header('Expires: 0'); // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
    header('Cache-Control: private', false);
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename="' . basename($url) . '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . strlen($r)); // provide file size
    header('Connection: close');
    echo $r;

But when the file is too big it displays the following message memory error what would be the solution for that?

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 139642559 bytes) in

Answer:

Don't use PHP to do this, but use Apache reverse proxy:

Configuration example (part) on server1 :

ProxyPass       /arquivos/  http://server2.example.com/

or you can work with file types:

<LocationMatch \.pdf$>
  ProxyPass http://server2.example.com/
</Locationmatch>

Extra:

If you need the IP on the client machine, on server2 , this code will help you:

<?php

echo $_SERVER['REMOTE_ADDR']; // IP do server1

if (array_key_exists('HTTP_X_FORWARDED_FOR', $server)) {
    if (strpos($server['HTTP_X_FORWARDED_FOR'],',') !== false) {
        $server['REMOTE_ADDR'] = current(explode(',', $server['HTTP_X_FORWARDED_FOR']));
    } else {
        $server['REMOTE_ADDR'] = $server['HTTP_X_FORWARDED_FOR'];
    }

    $_SERVER['REMOTE_ADDR'] = $server['REMOTE_ADDR'];
}

echo $_SERVER['REMOTE_ADDR']; // IP do Cliente
Scroll to Top