How to Download Images from URL using PHP

Do you want to download the images from the remote server to your local machine by using image URLs, here is the right blog which helps you. Here, I am going to provide two different examples for your reference.

Download Images from URL using File Handling

Here is the code to download images from the remote server to the local using PHP file handling method,

<?php
$imageUrl = "https://www.domain.com/media/catalog/product/mobile.jpg";
$filename = basename($imageUrl);
$localFilename = 'images/' . $filename;
file_put_contents($localFilename, file_get_contents($imageUrl));

In the above code,

  • The PHP function basename() is used to get the file name from the URL.
  • The PHP function file_get_contents() is used to read the image file from the URL and return the content as a string.
  • The PHP file_put_contents() is used to write the remote image data to a file in the local.

Download Images from URL using cURL

Here is the code to download images from the remote server to the local machine using cURL function,

function getFileContentsCurl($url) { 
    $ch = curl_init(); 
  
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_URL, $url); 
  
    $data = curl_exec($ch); 
    curl_close($ch); 
  
    return $data; 
}

$imageUrl = "https://www.domain.com/media/catalog/product/mobile.jpg";
$filename = basename($imageUrl);
$data = getFileContentsCurl($imageUrl);
$fp = 'images/' . $filename;
file_put_contents($fp, $data);

In the above code,

  • curl_init() is used to initialise an instance of cURL function in order to fetch the image data.
  • curl_setopt() is used to set the following cURL options.
    • CURLOPT_HEADER is used to ensure whether need to receive the headers or not.
    • CURLOPT_RETURNTRANSFER is used to transfer the data as a return value of curl_exec function rather than outputting it directly.
    • CURLOPT_URL is used to set the URL for the request.
  • Finally the data will be returned from the curl_exec() function and it will be saved in the local server by using the PHP function file_put_contents().

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *