PHP - 直接从 URL 将图像复制到我的服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6306935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - Copy image to my server direct from URL
提问by Ian
Possible Duplicate:
save image from php url using php
可能的重复:
使用 php 从 php url 保存图像
I want to have PHP code for following.
我想要以下 PHP 代码。
Suppose I have one image URL, for example, http://www.google.co.in/intl/en_com/images/srpr/logo1w.png
假设我有一个图片网址,例如http://www.google.co.in/intl/en_com/images/srpr/logo1w.png
If I run one script, this image will be copied and put on my server within folder having 777 rights.
如果我运行一个脚本,这个图像将被复制并放在我的服务器上具有 777 权限的文件夹中。
Is it possible? If yea, can you please give direction for same?
是否可以?如果是的话,你能给出相同的方向吗?
Thanks,
谢谢,
Ian
伊恩
回答by dotty
Two ways, if you're using PHP5 (or higher)
两种方式,如果您使用的是 PHP5(或更高版本)
copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.png');
If not, use file_get_contents
如果没有,请使用file_get_contents
//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.png", "w");
fwrite($fp, $content);
fclose($fp);
From this SO post
回答by Michael Robinson
From Copy images from url to server, delete all images after
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 = 'php';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here
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://www.foodtest.ru/images/big_img/sausage_3.jpg';
$imagename= basename($imgurl);
if(file_exists('./tmp/'.$imagename)){continue;}
$image = getimg($imgurl);
file_put_contents('tmp/'.$imagename,$image);
回答by Shakti Singh
$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);
you must have allow_url_fopen
set to on
你必须allow_url_fopen
设置为on
回答by Thariama
回答by Shay Anderson
$url = "http://www.example/images/image.gif";
$save_name = "image.gif";
$save_directory = "/var/www/example/downloads/";
if(is_writable($save_directory)) {
file_put_contents($save_directory . $save_name, file_get_contents($url));
} else {
exit("Failed to write to directory "{$save_directory}");
}