tags:

views:

45

answers:

2

Hello, given a direct link to an image, how do I store the actual image on a folder I have created on my server, using php?

Thanks

+4  A: 
$image_url = 'http://example.com/image.jpg';
$image = file_get_contents($image_url);
file_put_contents('/my/path/image.jpg', $image);

In a nut-shell, grab the image, store the image.. that easy.

Note: the allow_url_fopen php.ini setting must be set to true for the above example to work.

Mike B
Yep, that will work assuming that allow_url_fopen is set in php.ini. If it's not, then you'll have to use CURL to get the image, followed by file_put_contents() to write it.
BraedenP
Made that edit just as you made your comment :p
Mike B
thanks very much, works great
Dan Wilbur
+2  A: 

There is also the ever easy method of:

$img = 'http://www.domain.com/image.jpg';
$img = imagecreatefromjpeg($img);
$path = '/local/absolute/path/images/';
imagejpeg($img, $path);

The above comment regarding allow_url_fopen also holds true for this method. If you have a fairly restrictive host you might need to utilize cURL to get around this problem:

/**
 * For when allow_url_fopen is closed.
 * 
 * @param  string  $img       The web url to the image you wish to dl
 * @param  string  $fullpath  The local absolute path where you want to save the img
 */
function save_image($img, $fullpath) {
    $ch = curl_init ($img);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $binary_img = curl_exec($ch);
    curl_close ($ch);
    if (file_exists($fullpath)){
        unlink($fullpath);
    }

    $fp = fopen($fullpath, 'x');
    fwrite($fp, $binary_img);
    fclose($fp);
}
cballou
The first method your propose is going to involve a lot more overhead than simply copying the image down.
Frank Farmer
Alas, it allows you to manipulate the image with some GD trickery.
cballou