10

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?

0

1 Answer 1

22

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);
2
  • Be careful, if you use the "w" option it will overwrite everything in that file. Use "a" to append instead. Commented Apr 28, 2020 at 18:12
  • Appending a zip file is out of context here. Commented Mar 10, 2022 at 12:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.