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.

1 Comment

  1. Greetings from Los angeles! I’m boreed too teaars at work so I decided to check out
    your website on my iphone during lunch break. I really like
    the knowledge you present herre and can’t wait to take
    a look when I get home. I’m shocked att how fast your blog
    loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyways, awesome site!

    My web page ::

Leave a Reply

Your email address will not be published.