curl生成的cookie保存到浏览器

想将curl生成的cookie保存为浏览器识别的cookie

转:http://zhidao.baidu.com/link?url=FNBLsQ1m0W_gD0ym3b2B-65MRQMODHpQ2oFpgyjMUEOiAGIVNvLQOb8vBQJPPPVcApa7Re6GDPAZKMsi3MuoW9UO8zsox7wbLQHrOoSZs-C

然后用正则

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'website_url');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$results = curl_exec($ch);
curl_close($ch);
preg_match_all('|Set-Cookie: (.*);|U', $results, $arr);
$cookies = implode(';', $arr[1]);
var_dump($cookies);

?>

接着再用php中的setcookie方法设置浏览器的cookie

转:http://www.oschina.net/question/872425_103251

想整合一个网站和论坛的会员能够共同登陆,我现在做得是在网站登陆的时候 直接curl模拟post数据给论坛,但是论坛那边登陆成功之后 cookie并没有存到浏览器中。

<?php
$opt=array(
    CURLOPT_URL =>"http://www.baidu.com",
    CURLOPT_HEADER => 1,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_FRESH_CONNECT => 1,
    CURLOPT_FORBID_REUSE => 1
); 
$ch= curl_init();
curl_setopt_array($ch,$opt);
$result= curl_exec($ch);
curl_close($ch);
if(preg_match('/Set-Cookie:[\s]+([^=]+)=([^;]+)/i',$result,$match)) {
  $cookies[$match[1]] =$match[2];
  foreach($cookiesas$cookieKey=>$cookieVal) {
    setcookie($cookieKey,$cookieVal);
  }

}

demo

setcookie.php

  1 <?php
  2 var_dump($GLOBALS);
  3 #echo "123456";
  4 #exit;
  5 header("P3P: CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
  6 header("Set-Cookie: test=axis; domain=.a.com; path=/");
  7 ?>
  8 <script>
  9     alert(document.cookie);
 10 </script>

getcookie.php

  1 <?php
  2 $ch = curl_init();
  3 $post="username=test";
  4 curl_setopt($ch, CURLOPT_URL, 'setcookie.php');
  5 curl_setopt($ch, CURLOPT_HEADER, true);
  6 curl_setopt($ch, CURLOPT_NOBODY,false);
  7 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  8 curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
  9 $results = curl_exec($ch);
 10 curl_close($ch);
 11 print_r($results);
 12 preg_match_all('|Set-Cookie: (.*);|U', $results, $arr);
 13 $cookies = implode('=', $arr[1]);
 14 $test=explode("=",$cookies);
 15 setcookie($test[0],$test[1],time()+600);
 16 ?>

    A+
发布日期:2014年08月23日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: