海运的博客

PHP Curl使用Cookie

发布时间:November 16, 2014 // 分类:PHP // No Comments

发送或保存Cookie:

$ch = curl_init();
$url = 'https://www.haiyun.me/';
$cookiefile = '/tmp/cookie.txt';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); //保存cookie到此文件
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); //发送请求时从此文件获取cookie
curl_setopt($ch, CURLOPT_COOKIE, 'user=user; pass=pass'); //单独设置请求cookie
$content = curl_exec($ch);
curl_close($ch);

解析服务器设置的cookie并保存为变量:

$ch = curl_init('https://www.haiyun.me/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//输出返回head
curl_setopt($ch, CURLOPT_HEADER, 1);
$res = curl_exec($ch);
//切分内容和head
list($header, $body) = explode("\r\n\r\n", $res);
preg_match('/^Set-Cookie:\s*([^;]*)/mi', $header, $match);
parse_str($match[1], $cookies);
print_r($cookies);

从curl保存的cookie文件中解析cookie,文件格式见:http://www.cookiecentral.com/faq/#3.5
domain - The domain that created AND that can read the variable.
flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
path - The path within the domain that the variable is valid for.
secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
name - The name of the variable.
value - The value of the variable.

<?php
   $lines = file('/tmp/404344922.cookie');
   foreach($lines as $line) {
      if($line[0] != '#' && substr_count($line, "\t") == 6) {
         $tokens = explode("\t", $line);
         $tokens = array_map('trim', $tokens);
         $cookies[$tokens[5]] = $tokens[6];
      }
   }
   print_r($cookies);

设置保存cookie至文件:

<?php
   $file = fopen("/tmp/reg.cookie", "a");
   $domain = '.haiyun.me';
   $flag = 'TRUE';
   $path = '/';
   $secure = 'FALSE';
   $expiration = 0;
   $key = 'key';
   $value = 'value';
   $cookie = "$domain\t$flag\t$path\t$secure\t$expiration\t$key\t$value\n";
   fwrite($file, $cookie);
   fclose($file);

标签:none

评论已关闭

分类
最新文章
最近回复
  • 海运: 恩山有很多。
  • swsend: 大佬可以分享一下固件吗,谢谢。
  • Jimmy: 方法一 nghtp3步骤需要改成如下才能编译成功: git clone https://git...
  • 海运: 地址格式和udpxy一样,udpxy和msd_lite能用这个就能用。
  • 1: 怎么用 编译后的程序在家里路由器内任意一台设备上运行就可以吗?比如笔记本电脑 m参数是笔记本的...
  • 孤狼: ups_status_set: seems that UPS [BK650M2-CH] is ...
  • 孤狼: 擦。。。。apcupsd会失联 nut在冲到到100的时候会ONBATT进入关机状态,我想想办...
  • 海运: 网络,找到相应的url编辑重发请求,firefox有此功能,其它未知。
  • knetxp: 用浏览器F12网络拦截或监听后编辑重发请求,修改url中的set为set_super,将POS...
  • Albert: 啊啊啊啊啊啊啊啊啊 我太激动了,终于好了英文区搜索了半天,翻遍了 pve 论坛没找到好方法,博...