PHP cURL download image from URL or remote address

Download file, image from URL by using PHP cURL.

How to download an image or save it into the particular directory from a given remote URL by Using PHP cURL. In this post, I explain to you about this.

PHP cURL code save the image from URL when you want to copy an image dynamically from any remote server to the client-server.

The below code provides fetching images from remote websites or URLs.

PHP Code

<?php

if(isset($_POST['submitButton'])){
$url_to_image = $_POST['urlImage'];
$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);

echo '<h1>Your image is tranfered and download please check images folder in root. </h1>';

}else{
echo 'image not transfter...';
}

?>

HTML Code

<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="headingDownloadImage">
Download file, image from URL by using PHP cURL.
</h1>
</div>
</div>
<form action="submit.php" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-9">
<div class="inputField">
<input type="text" name="urlImage" />
</div>
</div>
<div class="col-md-3">
<input type="submit" name="submitButton" />
</div>
</div>
</form>
</div>

Download Sample Code :

Click Here

Explain of cURL Code

curl_init() – This method will initialize a cURL session.

curl_setopt() – This method will set option for transer cURL data. In this method we have use three option.

First CURLOPT_URL option for fetch data from URL.

Second is CURLOPT_RETURNTRANSFER option, it will return true on send data from URL in string format.

Third is CURLOPT_SSLVERSION.

curl_exec() – This method will execute cURL session.

curl_close() – This method will close cURL session.

Leave a Reply

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