cURL Download Zip File - " argument is not a valid File-Handle resource"

Howdy_McGee picture Howdy_McGee · Feb 24, 2015 · Viewed 7.8k times · Source

I'm trying to download a zip file from a server I host and store it on another server using PHP and cURL. My PHP looks like this:

set_time_limit( 0 );
$ci = curl_init();
curl_setopt_array( $ci, array(
    CURLOPT_FILE    =>  '/directory/images.zip',                // File Destination
    CURLOPT_TIMEOUT =>  3600,                                   // Timeout
    CURLOPT_URL     => 'http://example.com/images/images.zip'   // File Location
) );
curl_exec( $ci );
curl_close( $ci );

Whenever I run this I get the following error on the CURLOPT_URL line:

Warning: curl_setopt_array(): supplied argument is not a valid File-Handle resource in ...

If I visit the File Location directly in my browser, it downloads. Do I need to pass some kind of header information so that it knows to that it's a zip file? Is there some kind of way I can debug this?

Answer

Bijan picture Bijan · May 12, 2015

Your problem is that you have to pass a filehandle to CURLOPT_FILE, not the filepath. Here is a working example

$ci = curl_init();
$url = "http://domain.com/images/images.zip"; // Source file
$fp = fopen("/directory/images.zip", "w"); // Destination location
curl_setopt_array( $ci, array(
    CURLOPT_URL => $url,
    CURLOPT_TIMEOUT => 3600,
    CURLOPT_FILE => $fp
));
$contents = curl_exec($ci); // Returns '1' if successful
curl_close($ci);
fclose($fp);