web analytics

How to download image from URL using PHP? 2 methods explained.

Hello everyone, welcome to this short tutorial on how to download image from URL and save it on your server using PHP.

Method 1:

$url_to_image = 'http://oleaass.com/wp-content/uploads/2014/09/PHP.png';
$my_save_dir = 'images/';
$filename = basename($url_to_image);
$complete_save_loc = $my_save_dir . $filename;
file_put_contents($complete_save_loc, file_get_contents($url_to_image));

To download image from URL here

$url_to_image

is the URL of the image you want to download and

$my_save_dir

is absolute path to the folder where you want to save the image that you download image from URL. File is downloaded here using

file_get_contents

function and saved with

file_put_contents

function.

Method 2:

$url_to_image = 'http://cleversoft.co/wp-content/uploads/2013/08/senior-php-developer.jpg';

$ch = curl_init($url_to_image);

$my_save_dir = 'images/';
$filename = basename($url_to_image);
$complete_save_loc = $my_save_dir . $filename;

$fp = fopen($complete_save_loc, 'wb');

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

This method 2 to download image from URL uses cURL extension of PHP. As like method 1,

$url_to_image

is the URL of the image you want to download from URL and

$my_save_dir

is the absolute path to the folder where you want the image to be saved at.

In line 9 we are opening the file using

fopen

function and then getting the content into the file using an option

CURLOPT_FILE

targeted to

$fp

on line number 11.

Among these two, the first one is the one I will prefer.


Thank you. Take a moment to share 🙏