ghayourabbas
ghayourabbas

Reputation: 23

I want to save a image from remote URL to local system in PHP

this is my PHP code

<?php
$return = array();
$img_url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS";
$imageUrl = $img_url;
$dd = pathinfo($imageUrl);
$pic_name=  $dd['basename'];

@$rawImage = file_get_contents($imageUrl);

if($rawImage)
{
    file_put_contents("C:/xampp/htdocs/get_img/".$pic_name,$rawImage);

    echo 'Image Saved';
}
else
{

echo 'Error Occured';
}

?>

but for this URL from google images, this code is giving me this.
"Warning: file_put_contents(C:/xampp/htdocs/get_img/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS): failed to open stream: Resource temporarily unavailable in C:\xampp\htdocs\get_img\get1.php on line 12"

how can i save this image?

Upvotes: 0

Views: 619

Answers (2)

Yash Parekh
Yash Parekh

Reputation: 1529

Try this, It will help you

$imageLink = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS";
$random = mt_rand();
$size = getimagesize($imageLink);
$extension = image_type_to_extension($size[2]);
$filename = $random . $extension;
$path = "/images/";
file_put_contents(getcwd() . $path . $filename, file_get_contents($imageLink));

Upvotes: 0

Amarnasan
Amarnasan

Reputation: 15539

Just sanitize the filename before trying to create the file. Just create an MD5 string from the pic url.

file_put_contents("C:/xampp/htdocs/get_img/".md5($pic_name),$rawImage);

Upvotes: 0

Related Questions