php save image from url to server
In this article, we will learn how to save the image from the URL to the server. there two ways to download an image from the server. first is Save Image from URL using PHP and 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?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: