In this article, we will learn how to save images from URL using php. here we will give you a simple example of How to Save Images from URL using PHP.
there are two ways to download an image from the server. first is Save Image from URL using PHP and the second is Save Image from URL using cURL.
We will explain both ways. so you can see both ways.
Save Image from URL using PHP
<?php function download_image($new_file_name, $dir_path, $url) { if(!is_dir($dir_path)){ //create new dir if doesn't exist mkdir($dir_path); } $local_file_path = $dir_path .'/'.$new_file_name; if(copy($url, $local_file_path)) { return true; } } $new_file_name="new.png"; $dir_path="images/"; $url = 'http://www.example.com/image.png'; download_image($new_file_name,$dir_path,$url); ?>
Save Image from URL using cURL
<?php // Remote image URL $url = 'http://www.example.com/image.png'; // Image path $img = 'images/new.png'; // Save image $ch = curl_init($url); $fp = fopen($img, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); ?>
Please follow and like us: