PHP教程

PHP cURL 使用cookie 模拟登录

本文主要是介绍PHP cURL 使用cookie 模拟登录,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

使用cookie模拟登录,来查看需登录后才能浏览的页面 (get方式)
set_time_limit(0);
//目标url
$url = “http://www.aa.com/index.php/Home/task/add”;
//使用的cookie,路径自己修改
$cookie_file = DIR . “/”.‘cookies.txt’;
c o o k i e f i l e = r e a l p a t h ( cookie_file = realpath( cookief​ile=realpath(cookie_file);
c h = c u r l i n i t ( ch = curl_init( ch=curli​nit(url);
curl_setopt( c h , C U R L O P T H E A D E R , 0 ) ; c u r l s e t o p t ( ch, CURLOPT_HEADER, 0); curl_setopt( ch,CURLOPTH​EADER,0);curls​etopt(ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); //使用上面获取的cookies
r e s p o n s e = c u r l e x e c ( response = curl_exec( response=curle​xec(ch);
curl_close($ch);
echo $response;

使用cookie模拟post提交请求
set_time_limit(0);
//目标url
$url = ‘http://www.aa.com’;
//post查询条件
$fields = ‘claimType=01&orderBy=1&pageSize=300&page.webPager.action=refresh&page.webPager.pageInfo.totalSize=8000&page.webPager.pageInfo.pageSize=300&page.webPager.currentPage=1’;
//cookie文件
$cookie_file = DIR . “/”.‘cookies.txt’;
c o o k i e f i l e = r e a l p a t h ( cookie_file = realpath( cookief​ile=realpath(cookie_file);

c u r l = c u r l i n i t ( ) ; c u r l s e t o p t a r r a y ( curl = curl_init(); curl_setopt_array( curl=curli​nit();curls​etopta​rray(curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “POST”,
CURLOPT_COOKIEFILE => $cookie_file,
CURLOPT_COOKIEJAR => $cookie_file,
CURLOPT_HTTPHEADER => array(
“accept: /”,
“accept-encoding: gzip, deflate”,
“accept-language: zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2”,
“cache-control: no-cache”,
“connection: keep-alive”,
“content-type: application/x-www-form-urlencoded”,
//“cookie: $cookie”,
“origin: http://www.**.com”,
“pragma: no-cache”,
“referer: http://www.****.com”,
“user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36”,
“x-requested-with: XMLHttpRequest”
),
));

//url
curl_setopt($curl, CURLOPT_URL, u r l ) ; / / p o s t f i e l d s c u r l s e t o p t ( url); //post fields curl_setopt( url);//postfieldscurls​etopt(curl, CURLOPT_POSTFIELDS, $fields);

r e s p o n s e = c u r l e x e c ( response = curl_exec( response=curle​xec(curl);
e r r = c u r l e r r o r ( err = curl_error( err=curle​rror(curl);
h t t p c o d e = c u r l g e t i n f o ( httpcode = curl_getinfo( httpcode=curlg​etinfo(curl, CURLINFO_HTTP_CODE);
echo $response;

在这里插入图片描述

这篇关于PHP cURL 使用cookie 模拟登录的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!