Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

curl

zip

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?

like image 987
Howdy_McGee Avatar asked Feb 24 '15 17:02

Howdy_McGee


1 Answers

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);
like image 154
Bijan Avatar answered Sep 30 '22 13:09

Bijan