如何从PHP中的301重定向下载链接获取图像?
问题描述:
我试图用PHP下载this图像以用GD编辑它。我发现了许多用于图像链接的解决方案,但这是一个下载链接。如何从PHP中的301重定向下载链接获取图像?
编辑:
$curl = curl_init("http://minecraft.net/skin/Notch.png");
$bin = curl_exec($curl);
curl_close($curl);
$img = @imagecreatefromstring($bin);
这是我当前的代码。它显示“301永久移动”。是否有CURLOPT我必须设置?
答
$curl = curl_init("http://minecraft.net/skin/Notch.png");
// Moved? Fear not, we'll chase it!
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Because you want the result as a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$bin = curl_exec($curl);
curl_close($curl);
$img = @imagecreatefromstring($bin);
+0
是的,现在有用,谢谢。 =) – Aich
答
这里有一个选项可将图像直接保存到一个文件(而不是使用imagecreatefromstring
):
<?php
$fileName = '/some/local/path/image.jpg';
$fileUrl = 'http://remote.server/download/link';
$ch = curl_init($fileUrl); // set the url to open and download
$fp = fopen($fileName, 'wb'); // open the local file pointer to save downloaded image
curl_setopt($ch, CURLOPT_FILE, $fp); // tell curl to save to the file pointer
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // tell curl to follow 30x redirects
curl_exec($ch); // fetch the image and save it with curl
curl_close($ch); // close curl
fclose($fp); // close the local file pointer
有一个下载链接,图片链接没有什么区别。 –