27

Possible Duplicate:
Saving image from PHP URL

I have an image as a url link from the 3rd party web thumb site (IE http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com) What I would like to do is run a script that takes the image and saves it in a directory on my server using php. How to do this? would I use File Write?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mick
  • 2,840
  • 10
  • 45
  • 61
  • For my answer to work your installation of PHP must be compiled with the GD library (most are)... – Mark Lalor Sep 11 '10 at 23:18
  • See [ saving file using curl ](http://stackoverflow.com/questions/1006604/saving-file-using-curl/1006629#1006629). – Matthew Flaschen Sep 11 '10 at 23:20
  • Here's a tutorial that shows you how to do this in two ways. http://edmondscommerce.github.io/php/curl/php-save-images-using-curl.html – MZaragoza Apr 21 '15 at 01:35

2 Answers2

56

No need to create a GD resource, as someone else suggested.

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));

Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.

23

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

Community
  • 1
  • 1
Mark Lalor
  • 7,820
  • 18
  • 67
  • 106
  • 1
    This only works if allow_url_fopen is true. – Ólafur Waage Sep 11 '10 at 23:17
  • @Ólafur Waage sure, but by the same token, cURL only works if the curl extension is available and enabled on your system. – JAL Sep 11 '10 at 23:20
  • 3
    This is forcing GD to decode and encode the image for no reason. That also means it's *lossy*, and imagejpeg uses only 75% quality by default. All the OP asked for is a download (a bit-for-bit copy). – Matthew Flaschen Sep 11 '10 at 23:32