开发者

Storing an image from a link in PHP

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


$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.


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜