我需要用户的图像作为图像对象内的PHP。
显而易见的选择是执行以下操作:
$url = 'https://graph.facebook.com/'.$fb_id.'/picture?type=large';
$img = imagecreatefromjpeg($url);
这在我的测试服务器上工作,但在该脚本最终应该运行的服务器上不起作用(在那里allow_url_fopen被关闭)。
所以我尝试通过curl:
获取图像function LoadJpeg($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
curl_close($ch);
$img = imagecreatefromstring($fileContents);
return $img;
}
$url = 'https://graph.facebook.com/'.$fb_id.'/picture?type=large';
$img = LoadJpeg($url);
然而,这对facebook个人资料图片不起作用。
例如,使用curl从google.com加载google的logo效果非常好。
有人能告诉我为什么或告诉我如何实现我想要做的吗?
你必须设置
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
以这种方式找到图像如果没有它,你会得到一个没有图像的302响应代码,因为它在响应头的"url"字段中的另一个位置设置。
- 最简单的解决方案:打开
allow_url_fopen
Facebook最有可能匹配你的用户代理。欺骗它像…
// spoofing Chrome
$useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, wie z. B. Gecko) Chrome/13.0.782.215 Safari/525.13.";
$ch = curl_init();
// set user agent
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
// set the rest of your cURL options here
我不必提及这违反了他们的服务条款,可能会导致法律问题,对吗?此外,请确保您遵循他们的robots.txt
!