开发者

How to copy a remote image to my website directory?

I post pictures from other websites and I would rather have those on my servers, in case their server dies all of a sudden开发者_StackOverflow社区. Say the file is located at "www.www.www/image.gif", how would I copy it to my directory "images" safely?

I write in PHP.

Thanks!


The following should work:

// requires allow_url_fopen
$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image);

or the cURL route:

$ch = curl_init('http://www.url.com/image.jpg');
$fp = fopen('/images/image.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);


If your server is configured to support http:// file paths, you could use file_get_contents.

If that doesn't work, the second simplest way is by using curl for which you will certainly find full-fledged download scripts.

Some servers you pull images from may require a User-agent that shows that you are a regular browser. There is a ready-made class in the User Contributed Notes to curl that handles that, and provides a simple DownloadFile() function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜