昨天采集美女图片时碰到了防盗链,通过curl破解防盗链。

<?php
include 'phpQuery.class.php';
set_time_limit(0);
$strUrl = 'http://www.mm131.com/qingchun/list_1_1.html';

$dataStr = file_get_contents($strUrl);

$htmlStr = phpQuery::newDocument($dataStr);
$bodyHtmlStr = pq('.public-box dd');
$arrHtml = array();
foreach($bodyHtmlStr as $key=>$val){
	$arrHtml[] = pq($val)->attr('href');
}

foreach($arrHtml as $key=>$val){
	
$pageContentData = explode('/',str_replace('.html','',$val));

$contentId = $pageContentData[4];

$dataStr = file_get_contents($val);
$htmlStr = phpQuery::newDocument($dataStr);
$bodyHtmlStr = pq('.content-page a');
foreach($bodyHtmlStr as $k=>$v){
	$arrHtmlContent[] = pq($v)->attr('href');
}

$imgNum = count($arrHtmlContent);
$imgUrl = array();
for($i=1;$i<=$imgNum;$i++){
	$imgUrl[] = 'http://img1.mm131.com/pic/'.$contentId.'/'.$i.'.jpg';
}
$arrHtmlContent =array();
 
$arrHtmlContent[]= str_replace('http://www.mm131.com/qingchun/','',$val);
$contetnImgUrl = array_unique($arrHtmlContent);

	foreach($imgUrl as $k=>$v){
	//处理防盗链 主要是referer	
		$ch = curl_init($v);  
		curl_setopt($ch, CURLOPT_REFERER, 'http://www.mm131.com/');  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);   
		$response = curl_exec($ch);
		$fp = fopen('img/'.$contentId.'_'.$k.'.jpg', 'w');
		fwrite($fp,$response);
		fclose($fp);
		if (curl_errno($ch) > 0) {
			exit("CURL ERROR:$v " . curl_error($ch));
		}
		curl_close($ch);
		
	}
}
想看美女的可以将代码运行一下哦!自己将PHPquery下载就可以了!

你可能感兴趣的:(curl,防盗链,美图)