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 = '';
$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


is the URL of the image you want to download and


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


function and saved with



Method 2:

$url_to_image = '';

$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);

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


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


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


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


targeted to


on line number 11.

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

Author: Tanmay Chakrabarty

Tanmay Chakrabarty is a former CSE student, currently working as a Senior Software Engineer with 5+ years of experience in the field of Web Application development in PHP+MySQL platform with strong skills in Javascript, JQuery, JQuery UI and CSS. He tries to write notes every week but fails due to heavy loads of duty.

Recommended Recommends


Contact Us