Answers:
如果您allow_url_fopen
设置为true
:
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
其他使用cURL:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$_GET
包含图像URL的变量http://example.com/fetch-image.php?url=http://blabla.com/flower.jpg
。在此示例中,您可以只调用$_GET['url']
PHP脚本,如下所示:$ch = curl_init($_GET['url']);
。
copy('http://example.com/image.php', 'local/folder/flower.jpg');
allow_url_fopen
)。
$content = file_get_contents('http://example.com/image.php');
file_put_contents('/my/folder/flower.jpg', $content);
在这里,该示例将远程图像保存到image.jpg。
function save_image($inPath,$outPath)
{ //Download images from remote server
$in= fopen($inPath, "rb");
$out= fopen($outPath, "wb");
while ($chunk = fread($in,8192))
{
fwrite($out, $chunk, 8192);
}
fclose($in);
fclose($out);
}
save_image('http://www.someimagesite.com/img.jpg','image.jpg');
Vartec使用cURL 的答案对我不起作用。确实如此,由于我的特定问题,略有改进。
例如,
如果服务器上存在重定向(例如,当您尝试保存Facebook个人资料图像时),则需要设置以下选项:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
完整的解决方案成为:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
我无法使用其他任何解决方案,但可以使用wget:
$tempDir = '/download/file/here';
$finalDir = '/keep/file/here';
$imageUrl = 'http://www.example.com/image.jpg';
exec("cd $tempDir && wget --quiet $imageUrl");
if (!file_exists("$tempDir/image.jpg")) {
throw new Exception('Failed while trying to download image');
}
if (rename("$tempDir/image.jpg", "$finalDir/new-image-name.jpg") === false) {
throw new Exception('Failed while trying to move image file from temp dir to final dir');
}
参见file()
PHP手册:
$url = 'http://mixednews.ru/wp-content/uploads/2011/10/0ed9320413f3ba172471860e77b15587.jpg';
$img = 'miki.png';
$file = file($url);
$result = file_put_contents($img, $file)
file_put_contents
等等