4

I am using cURL to retrieve an image, rename it and store it locally. The images comes up as 0 byte file, no matter, whether I use cURL, like so:

$strImageUrl = curl_init($strImageUrlSource);
$fp = fopen($strTargetImage, 'wb');
curl_setopt($strImageUrl, CURLOPT_FILE, $fp);
curl_setopt($strImageUrl, CURLOPT_HEADER, 0);
curl_exec($strImageUrl);
curl_close($strImageUrl);
fclose($fp);

or file_put/get. like so:

file_put_contents($strImageName, file_get_contents($strImageUrlSource));

The URL I am retrieving is:

<img src='http://i1.au.reastatic.net/150x112/73fa6c02a92d60a76320d0e89dfbc1a36a6e46c818f74772dec65bae6959c62f/main.jpg' width="150" height="112" alt="Wondecla, address available on request" title="Wondecla, address available on request" />

I can save this image properly manually. When looking at the properties in FireFox it shows three entries:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFgAAABYBAMAAACDuy0HAAAAG1BMVEX+/v4BAQH///8KCgoDAwN/f3/19fWAgID8... etc

http://i1.au.reastatic.net/150x112/73fa6c02a92d60a76320d0e89dfbc1a36a6e46c818f74772dec65bae6959c62f/main.jpg

data:image/png;base64,iVBORw0KG ... etc.

What am I doing wrong here?

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
MaxG
  • 187
  • 3
  • 11
  • It's possible there was a timeout, redirect, hotlink protection or something of that nature. You might want to play with other curl options allowing redirects, etc. See my solution here http://stackoverflow.com/a/18927806/722796 – PJ Brunet Sep 21 '13 at 01:06
  • BTW this deletes all the size zero images in Linux: find /home/somewhere/images -type f -size 0 -exec rm {} \; – PJ Brunet Sep 21 '13 at 01:11

2 Answers2

1

This works:

Using file_get_contents

$image = 'http://i1.au.reastatic.net/150x112/73fa6c02a92d60a76320d0e89dfbc1a36a6e46c818f74772dec65bae6959c62f/main.jpg';

$imageName = pathinfo( $image, PATHINFO_BASENAME );

file_put_contents( $imageName, file_get_contents( $image ) );

Using CURL

$image = 'http://i1.au.reastatic.net/150x112/73fa6c02a92d60a76320d0e89dfbc1a36a6e46c818f74772dec65bae6959c62f/main.jpg';

$imageName = pathinfo( $image, PATHINFO_BASENAME );

$ch = curl_init();

curl_setopt( $ch, CURLOPT_URL, $image );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

$source = curl_exec( $ch );
curl_close( $ch );

file_put_contents( $imageName, $source );

Hope this helps.

web-nomad
  • 6,003
  • 3
  • 34
  • 49
0

Use var_dump() to debug. What do you see when you

var_dump(file_get_contents('http://i1.au.reastatic.net/150x112/73fa6c02a92d60a76320d0e89dfbc1a36a6e46c818f74772dec65bae6959c62f/main.jpg'));
Youri
  • 495
  • 1
  • 4
  • 18