Question

I am using php to get an image from url and copy it to my server but got an error saying there is no such file

Image example:

http://www.google.co.in/intl/en_com/images/srpr/logo1w.png

Here is the solution I am using:

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);

I am getting the following error. Did i do anything wrong?

fopen(/location/to/save/image.jpg): failed to open stream: No such file or directory
Was it helpful?

Solution 2

function download_image($url,$destination_path = '')
{  
    // CHECKS IF CURL DOES EXISTS. SOMETIMES WEB HOSTING DISABLES FILE GET CONTENTS
    if (function_exists('curl_version'))
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $content = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

    } else
    {
        $content = file_get_contents($url);
    }
    // CHECKS IF DIRECTORY DOESNT EXISTS AND DESTINATION PATH IS NOT EMPTY
    if(!file_exists($destination_path) && $destination_path != ''){
        mkdir($destination_path, 0755, true);  
    }
    // ATTEMPT TO CREATE THE FILE
    $fp = fopen($destination_path.'/'.date('YmdHis').".jpg", "a+");
    fwrite($fp, $content);
    fclose($fp); 
}

download_image('http://davidwalsh.name/wp-content/themes/jack/images/treehouse-1.png','images');

OTHER TIPS


✓ This worked for me.


Try it without the /location/to/save/

The file will be saved in the same folder you run the script in.

Such as:

<?php

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("image_google.jpg", "w");
fwrite($fp, $content);
fclose($fp);

?>

The folder (/location/to/save in here) should exist. You also need write permissions in it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top