php curl 的 cookie 存储到文件和变量 - Alex的博客

Alex的博客

本博客的文章均为原创,是本人从事行业多年来所遇见一些小问题的解决心得,希望可以帮助到大家!



php curl 的 cookie 存储到文件和变量

//cookie保存到文件然后再提交

$login_url='http://www/baidu.com';    //提交地址

$post_fields = 'user_name=user&password=pwd&remember_password=0';    //post提交数据

$cookie_file = tempnam('./temp','cookie');    //在temp目录创建一个以cookie开头的唯一文件名

$ch = curl_init($login_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);    //cookie保存到文件
curl_exec($ch);
$httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);    //http状态
curl_close($ch); 


//调用并提交cookie


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);    //调用cookie文件

$contents = curl_exec($ch);
$httpCode2 = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);




//cookie保存到变量


$ch = curl_init($login_url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$contentsx=curl_exec($ch);
$httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode!='200') {
    exit();
}
preg_match("/Set-Cookie:(.*)Vary:/is",$contentsx,$cookarr);    // 正则提取cookie
$cookie_file=$cookarr['1']; //cookie赋值给变量


//调用存储cookie的变量并提交

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIE,$cookie_file);    //调用存储cookie的变量
$contents = curl_exec($ch);
$httpCode2 = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);


浏览975  评论0  Alex于 2015-12-21 14:09
发言