经常会用到一些采集网上的资源,普通网站很好采,get_file_contents()/c_url(). 有的网站会有登陆后才能采集,需要带cookie请求获取(登陆网站相同方法),下面记录一下使用方法,供参考。
<?PHP
header('content-type:text/html;charset=utf8');
define("COOKIE_PATH",dirname(__FILE__).'/cookie.txt');
//获取COOKIE
function curl_get_cookie($url){
$ch = curl_init($url); //初始化
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
curl_setopt($ch, CURLOPT_HEADER, 0); //不返回header部分
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); //返回字符串,而非直接输出
curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIE_PATH); //存储cookies
curl_exec($ch);
curl_close($ch);
} #带COOKIE请求
function curl_cookie_request($url,$post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
curl_setopt($ch, CURLOPT_HEADER, 0);
if($post) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post))
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIE_PATH); //使用上面获取的cookies
$response = curl_exec($ch);
curl_close($ch);
return $response;
}