简单解决微信文章图片防盗链问题

yipeiwu_com6年前PHP代码库

微信对外提供了API接口,让我们可以通过授权的方式获取到自己公众号里面的文章,或者你也可以通过爬虫去抓取微信的文章,但是微信的图片默认是不允许外部调用的

这里我找到了两种方案

第一种

在JS中提前把图片加载到本地,然后从本地缓存中读取图片

var showImg = function (url) {
  var frameid = 'frameimg' + Math.random();
  window.img = '<img id="img" src=\'' + url + '?' + Math.random() + '\' /><script>window.onload = function() { parent.document.getElementById(\'' + frameid + '\').height = document.getElementById(\'img\').height+\'px\'; }<' + '/script>';
  return '<iframe id="' + 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 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/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的方式,测试过可以用

相关文章

php tp验证表单与自动填充函数代码

复制代码 代码如下: <?php class FormModel extends Model { // 自动验证设置 /* * 一:自动验证 自动验证的定义是这样的:array(f...

php读取html并截取字符串的简单代码

复制代码 代码如下:<?php $title='【宜配屋www.yipeiwu.com】'; $hello='jb51.net!'; $file=file_get_contents...

eAccelerator的安装与使用详解

一、PHPeAccelerator安装去https://github.com/eaccelerator/eaccelerator/downloads下载最新版安装包,解压安装包,进入解压...

PHP调用全国天气预报数据接口查询天气示例

本文实例讲述了PHP调用全国天气预报数据接口查询天气。分享给大家供大家参考,具体如下: 基于PHP的聚合数据全国天气预报API服务请求的代码样例 本代码示例是基于PHP的聚合数据全国天气...

收集的DedeCMS一些使用经验

以下的都是转过来的,只是参补其官方的不足,其实它历害的功能没谈到,呵呵,保留一下先 1、在文章列表中,有的标题被截断了,怎么样能用点结尾?   用什么样的代码可以让鼠...