Save image from URL using cURL

I need to save the image with url directly on my server, I tried many methods, but everything seems to be not working properly. file_put_contents($file_location, file_get_contents($image_url));does not allow me to get an error in the found file directory. Simple fopenand fwritecontinue to return a damaged image. This one worked, but it saves the returning html file instead of the jpg file.

function getimg($url) {         
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent);         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);         
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 

$imgurl = 'http://some/url/to/image.jpg'; 
$imagename= basename($imgurl);
if(file_exists('./image/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('image/'.$imagename,$image);

Is something missing?

Thank.

+5
source share
2 answers

Your code is working correctly. It downloads an image from a given URL.

Your problem will be in the way where the image will be saved.

if(file_exists('./image/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('image/'.$imagename,$image);

./image/ , file_put_contents.

+3

:

<?php

file_put_contents("/var/www/test/test.png", file_get_contents("http://www.google.com/intl/en_com/images/srpr/logo3w.png"));

?>

allow_url_fopen, . . http://php.net/manual/en/features.remote-files.php

+2

All Articles