Download file with cURL & PHP

CURLOPT_RETURNTRANSFER is a simple way of copying a file from a remote server onto your own. However, if you're downloading a large file you may hit memory limits because the entire contents of the download have to be read to memory before being saved.

Note: Even if your memory limit is set extremely high, you would be putting unnecessary strain on your server by reading in a large file straight to memory.

Instead you can write the download straight to a file stream using CURLOPT_FILE.

$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);