Question

I am trying to download images using curl from php, however instead of saving the image to the server it is just outputting random characters to the web browser screen, here's the code

$final['IMAGE'] = 'http://www.google.com/images/srpr/logo3w.png';

$imagename = trim(basename($final['IMAGE']));

$url  = $final['IMAGE'];
$path = '/media/import/';
$path .= $imagename;

$fp = fopen($path, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);
Was it helpful?

Solution

curl_exec($ch); will print the output directly to the screen. You can stop his behavior when using the CURLOPT_RETURNTRANSFER-option:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

See the PHP-manual "curl_setopt" for more information.

Edit

This little script downloads the file to a writable directory:

// file handler
$file = fopen(dirname(__FILE__) . '/test.png', 'w');
// cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'somethinsomething.com/something.png');
// set cURL options
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// set file handler option
curl_setopt($ch, CURLOPT_FILE, $file);
// execute cURL
curl_exec($ch);
// close cURL
curl_close($ch);
// close file
fclose($file);

This time it's the CURLOPT_FILE-option that does the trick. More information can be found on the same link as before.

OTHER TIPS

If you're sure they will be .png, you can make use of imagecreatefromstring() and imagepng():

$c = curl_init( $final['IMAGE'] );
curl_setopt( $c, CURLOPT_HEADER, 0 );
curl_setopt( $c, CURLOPT_RETURNTRANSFER, 1 );
$binary = curl_exec( $c );
curl_close( $c );

$imagename = trim(basename($final['IMAGE']));
$url  = $final['IMAGE'];
$path = '/media/import/';
$path .= $imagename;

$img = imagecreatefromstring( $binary );
imagepng( $img, $path, 0 );

You can just use copy():

copy("http://www.google.com/images/srpr/logo3w.png", "/media/import/logo3w.png");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top