PHP函数:CURL抓取网站内容的,支持301 302跳转

我们在抓取网站内容的时候,经常遇到稀奇古怪的防盗链,比如上次碰到一个站的图片地址是假的,访问后要301跳转一次才到真正的图片路径,这个真实的路径又做了防盗措施,判断referer是不是上个假的图片地址。用curl试了几次,终于整出一个函数,效果不错。


$curl_loops = 0;//避免死了循环必备
02
$curl_max_loops = 3;
03
  
04
function curl_get_file_contents($url, $referer='') {
05
global $curl_loops, $curl_max_loops;
06
$useragent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
07
if ($curl_loops++ >= $curl_max_loops) {
08
  $curl_loops = 0;
09
  return false;
10
}
11
$ch = curl_init();
12
curl_setopt($ch, CURLOPT_URL, $url);?curl_setopt($ch, CURLOPT_HEADER, true);
13
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
14
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
15
curl_setopt($ch, CURLOPT_REFERER, $referer);
16
$data = curl_exec($ch);
17
$ret = $data;
18
list($header, $data) = explode("\r\n\r\n", $data, 2);
19
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
20
$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
21
curl_close($ch);
22
if ($http_code == 301 || $http_code == 302) {
23
  $matches = array();
24
  preg_match('/Location:(.*?)\n/', $header, $matches);
25
  $url = @parse_url(trim(array_pop($matches)));
26
  if (!$url) {
27
  ?$curl_loops = 0;
28
  ?return $data;
29
  }
30
  $new_url = $url['scheme'] . '://' . $url['host'] . $url['path']
31
   . (isset($url['query']) ? '?' . $url['query'] : '');
32
  $new_url = stripslashes($new_url);
33
  return curl_get_file_contents($new_url, $last_url);
34
} else {
35
  $curl_loops = 0;
36
  list($header, $data) = explode("\r\n\r\n", $ret, 2);
37
  return $data;
38
}
39
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值