简单解决微信文章图片防盗链问题
微信对外提供了API接口,让我们可以通过授权的方式获取到自己公众号里面的文章,或者你也可以通过爬虫去抓取微信的文章,但是微信的图片默认是不允许外部调用的
这里我找到了两种方案
第一种
在JS中提前把图片加载到本地,然后从本地缓存中读取图片
varshowImg=function(url){
varframeid='frameimg'+Math.random();
window.img='<imgid="img"src=\''+url+'?'+Math.random()+'\'/><script>window.onload=function(){parent.document.getElementById(\''+frameid+'\').height=document.getElementById(\'img\').height+\'px\';}<'+'/script>';
return'<iframeid="'+frameid+'"src="javascript:parent.img;"frameBorder="0"scrolling="no"width="100%"></iframe>';
}
第二种
用PHP模拟浏览器请求
$url=$request->input('url');
$ch=curl_init();
$httpheader=array(
'Host'=>'mmbiz.qpic.cn',
'Connection'=>'keep-alive',
'Pragma'=>'no-cache',
'Cache-Control'=>'no-cache',
'Accept'=>'textml,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8',
'User-Agent'=>'Mozilla/5.0(WindowsNT6.3;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/41.0.2272.89Safari/537.36',
'Accept-Encoding'=>'gzip,deflate,sdch',
'Accept-Language'=>'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
);
$options=array(
CURLOPT_HTTPHEADER=>$httpheader,
CURLOPT_URL=>$url,
CURLOPT_TIMEOUT=>5,
CURLOPT_FOLLOWLOCATION=>1,
CURLOPT_RETURNTRANSFER=>true
);
curl_setopt_array($ch,$options);
$result=curl_exec($ch);
curl_close($ch);
header('Content-type:image/jpg');
echo$result;
exit;
两种方法类似,我目前用的JS的方式,测试过可以用