cURL is used to make a connection to an external source to retrieve the content at the source. What most people new to cURL don’t realize is that it can be used to retrieve any content, including images.
Display An Image In Browser After Retrieval Via cURL
Let’s take a look at an example of displaying a image in browser after using cURL to grab it.
//The cURL stuff...
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/randomimage.jpg');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$picture = curl_exec($ch);
//Display the image in the browser
Yes, believe it or not it is actually that simple. Unfortunately I can’t provide an example any more, but it does work… Honest. Scouts honour and everything.
Let’s also go through what is going on a little. First we initialize cURL, we set the URL, then we tell it we don’t want the header information. We tell it we want to return the information, and we also state we want the transfer to be binary. We then execute it & store the result in a variable, and close/destroy the cURL connection/handler.
Finally we tell the browser that the content we are going to hand it is a jpeg image. You could of course use a MIME type grabbed from the image. Then we echo the binary information inside the variable, that is then interpreted as an image thanks to the content type.
Saving An Image Retrieved Via cURL
Let’s take a look at how to save the image instead of sending it to the browser.
//cURL code is exactly the same as before...
$fh = fopen('filename.jpg', 'x');
A little more complicated that the previous example, but if you are familiar with PHP file operations it’s still very simple. I can’t really give an example for this one, as you won’t be able to see the result. Trust me though, it works. 😉
Let’s go through this one a little too. The cURL section is exactly the same as before so we don’t need to cover that. First we use
fopen to create a file handler & tell PHP what file to write too.
x tells PHP to create the file if it doesn’t exist, but to error out if it does already exist. Then we use
fwrite to write the raw binary data held in the variable
$picture to the file. We then close & destroy the file handler by using
One of the main reasons to use cURL to save or display a remote image is that some servers/hosts have
allow_url_fopen turned off. This means functions like
fopen can’t open files held on external servers.
You could go into the whole copyright issue of displaying other people’s images etc, but I’m not going to get started on my thoughts about that. Just be careful with this kind of script & use it with care.