php教程

利用curl函数抓取网站数据,仿造IP+伪造来源+防屏蔽

php教程 51源码 2022-11-02 人阅读

1、伪造客户端IP地址,伪造访问referer:(一般情况下这就可以访问到数据了)

curl_setopt($curl, CURLOPT_HTTPHEADER, ['X-FORWARDED-FOR:110.85.108.185', 'CLIENT-IP:110.85.108.185']);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.demo.com/test.php');

2、如是上面的还是不行,可能是别人抓到了真实IP,这时候我们就使用代{过}{滤}理访问。

#  详细方式
curl_setopt($curl, CURLOPT_PROXY, 'x.x.x.x');    //代{过}{滤}理服务器地址
curl_setopt($curl, CURLOPT_PROXYPORT, 80);             //代{过}{滤}理服务器端口
//curl_setopt($curl, CURLOPT_PROXYUSERPWD, ':'');      //http代{过}{滤}理认证帐号,username:password的格式
curl_setopt($curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); //使用http代{过}{滤}理模式
#  简写方式
curl_setopt($curl, CURLOPT_PROXY, 'http://x.x.x.x:80');

3、还有一种就是用浏览器可以访问,用curl不行。(对方检查了useragent,如果没有就认为是非法来源等验证了)

$useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 ';
$useragent.= '(KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36';
curl_setopt($curl, CURLOPT_USERAGENT, $useragent);

PHP完整Curl抓取数据函数:

/**
* 请求接口
* [url=home.php?mod=space&uid=718080]@access[/url] public
* [url=home.php?mod=space&uid=952169]@Param[/url] string $url 请求地址
* @param array $data 提交参数 没有get 有post
* [url=home.php?mod=space&uid=155549]@Return[/url] bean|array
*/
public function send($url='')
{  
set_time_limit(0);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['X-FORWARDED-FOR:127.0.1.1', 'CLIENT-IP:127.0.1.1']);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.demo.com/demo.php');
curl_setopt($curl, CURLOPT_PROXY, 'http://127.0.0.1:80');
$useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 ';
$useragent.= '(KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36';
curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
if(!empty($data) && is_array($data)){
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
$html = curl_exec($curl);
if($error=curl_errno($curl)){
return false;
}
curl_close($curl);
return $html;
}
版权声明:文章搜集于网络,如有侵权请联系本站,转载请说明出处:https://www.51yma.cn/jiaocheng/php/374.html
文章来源:
标签 PHP函数