Search code examples
phpdownloadserver-to-server

In PHP is there a way that the server can download a file directly to the filesystem?


I need my server to download a file and write it to the server's filesystem. The problem is that all the PHP examples I've seen download the file into server RAM and then write to a file.

Since I'm dealing with large files, I'd like PHP to read the file from the other server and immediately write what it reads to a local file.


Solution

  • Use curl like this:

    <?php
     $url  = 'http://www.example.com/a-large-file.zip';
     $path = '/path/to/a-large-file.zip';
    
     $fp = fopen($path, 'w');
    
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_FILE, $fp);
    
     $data = curl_exec($ch);
    
     curl_close($ch);
     fclose($fp);
    ?>