Reputation: 533
I have a code in cURL that should copy an image from a URL to my server:
$curl = curl_init( $url );
$file = fopen( $imageURL , 'wb' );
curl_setopt( $curl , CURLOPT_FILE , $file );
curl_setopt( $curl , CURLOPT_HEADER , true );
curl_setopt( $curl , CURLOPT_FOLLOWLOCATION , true );
curl_exec( $curl );
curl_close( $curl );
fclose( $file );
it doesn't work correctly but file_put_contents()
does. Is there something wrong with my cURL code?
Upvotes: 0
Views: 2498
Reputation: 57680
Dont set CURLOPT_HEADER
to true. This will include the header in the output. So your image file will contain response header + image data. Remove that line or set it false
.
Upvotes: 1
Reputation: 986
There are multiple solutions, cURL probably isn't the best.
$remote_img = 'http://www.somwhere.com/images/image.jpg';
$img = imagecreatefromjpeg($remote_img);
$path = 'images/';
imagejpeg($img, $path);
Would work nicely, but if you are set on cURL, try this:
$ch = curl_init ($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);
if(file_exists($fullpath)){
unlink($fullpath);
}
$fp = fopen($fullpath,'x');
fwrite($fp, $rawdata);
fclose($fp);
That should work as well.
Best of luck!
Upvotes: 5