5

I need to save an image from url directly to my server, i've tried many methods but all seems doesn't work properly. file_put_contents($file_location, file_get_contents($image_url)); keeps me getting no file directory found error. Simple fopen and fwrite keeps returning corrupted image. This one worked, but it keeps returning html file instead of 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);

Something is missing?

Thanks.

1
  • Are you sure it's an image file you're trying to download and not a web page? What does the HTML file you get contain? Commented Nov 1, 2011 at 6:37

2 Answers 2

3

Your code works correct. It downloads the image from the given url.

Your issue will be in the path where the image is stored.

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

In the above code check the path ./image/ and give the path as in the file_put_contents path.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry my bad, i've found the solution, the URL(image name) has 'space' char, so i have to replace them with '%20'. Thanks for reply.
2

This method works:

<?php

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

?>

You need to enable allow_url_fopen and it's the simplest method. See http://php.net/manual/en/features.remote-files.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.