海运的博客

PHP Curl使用Cookie

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

发送或保存Cookie:

$ch = curl_init();
$url = 'http://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('http://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

评论已关闭

分类
最新文章
最近回复
  • 海运: 正常情况下编译整个内核执行make menuconfig后就不会出现此提示,当单独编译单个模块...
  • oijq: 就是用的armbian的配置文件哈,按你的教程做的,在执行make LOCALVERSION=...
  • 海运: 使用armbian的配置文件,其它添加或修改自己懂的部分,不懂的就不要碰了。
  • oijq: 编译时这些选项全部选Y吗?Actions Semi Platforms (ARCH_ACTIO...
  • 海运: n1编译bbr内核模块参考这个:https://www.haiyun.me/archives/...
  • jiqz: make M=net/ipv4/ CONFIG_TCP_CONG_BBR=m modules编...
  • ruralhunter: 哦,文档里应该是对的,是.config
  • ruralhunter: cp /mnt/boot/config-4.18.7-aml-s9xxx .config这里应...
  • 海运: 你是编译不成功呢?还是编译后不能运行呢?还是运行后不能访问web界面呢?
  • 白墨: 可能不清楚就是编译安装后启动后访问不了web界面