Categories: Development

Save image using cURL with PHP

Often cURL in PHP is used to download whole webpages, another great use is downloading and saving images.

Using cURL to save images is used over the file_put_content(file_get_contents()) because you can apply more parameters to the request most important being able to set a user agent.

With cURL I can state “who I am” when I make the request for the image.

You can hide your scraping bot and pretend you’re just a regular web user…

curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)");

Or have some fun:

curl_setopt($ch, CURLOPT_USERAGENT, "Grabbing image in 3, 2, 1... Thanks");

Obviously a regular user wouldn’t be hitting as many requests in little time as a scraping bot would.

By using

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

The image is returned as a raw binary string and not outputted.

curl_setopt($ch, CURLOPT_HEADER, false);

Means no header is in the output.

$fp = fopen($save_as, 'x');
fwrite($fp, $raw_data);
fclose($fp);

Handles the saving of the raw image data into the actual viewable image file.

The full code is:

<?php
$image_url = 'https://website.com/img/1234.jpg';
$save_as = 'img/1234.jpg';
$ch = curl_init($image_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)");
$raw_data = curl_exec($ch);
curl_close($ch);
$fp = fopen($save_as, 'x');
fwrite($fp, $raw_data);
fclose($fp);

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago