发送或保存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