PHP 中的 Netscape HTTP Cooke 文件解析器
我最近需要创建一个函数来从NetscapeHTTPcookie文件中读取和提取cookie。该文件由PHP在运行CURL时生成(启用了适当的选项),可用于后续的CURL调用。可以读取此文件以查看在CURL完成运行后创建了哪些cookie。例如,这是在典型的CURL调用期间可能创建的那种文件。
# Netscape HTTP Cookie File # http://curl.haxx.se/rfc/cookie_spec.html # This file was generated by libcurl! Edit at your own risk. www.example.com FALSE / FALSE 1338534278 cookiename value
前几行是注释,因此可以忽略。cookie数据由以下项目组成(按照它们在文件中出现的顺序。
domain-创建并可以读取变量的域。
标志-一个TRUE/FALSE值,指示给定域中的所有机器是否都可以访问该变量。该值由浏览器自动设置,具体取决于您为域设置的值。
path-域内变量有效的路径。
安全-一个TRUE/FALSE值,指示是否需要与域的安全连接来访问变量。
到期-变量将到期的UNIX时间。
name-变量的名称。
value-变量的值。
因此,用于提取此信息的函数将如下所示。它以一种非常简单的方式工作,并且基本上返回找到的cookie数组(如果有)。我最初尝试使用哈希字符来确定注释行的开头,然后尝试提取任何其他包含内容的内容。然而,事实证明,某些站点会在开头添加带有哈希字符的cookie(是的,即使对于URL参数也是如此)。因此,通过查看其中是否有6个制表符来检测cookie行会更安全。然后由制表符分解并转换为数据项数组。
/**
* Extract any cookies found from the cookie file. This function expects to get
* a string containing the contents of the cookie file which it will then
* attempt to extract and return any cookies found within.
*
* @param string $string The contents of the cookie file.
*
* @return array The array of cookies as extracted from the string.
*
*/
function extractCookies($string) {
$cookies = array();
$lines = explode("\n", $string);
//遍历行
foreach ($lines as $line) {
//我们只关心有效的cookiedef行
if (isset($line[0]) && substr_count($line, "\t") == 6) {
//获取数组中的令牌
$tokens = explode("\t", $line);
//修剪令牌
$tokens = array_map('trim', $tokens);
$cookie = array();
//提取数据
$cookie['domain'] = $tokens[0];
$cookie['flag'] = $tokens[1];
$cookie['path'] = $tokens[2];
$cookie['secure'] = $tokens[3];
//将日期转换为可读格式
$cookie['expiration'] = date('Y-m-d h:i:s', $tokens[4]);
$cookie['name'] = $tokens[5];
$cookie['value'] = $tokens[6];
//记录饼干。
$cookies[] = $cookie;
}
}
return $cookies;
}为了测试这个功能,我使用了以下代码。这需要一个URL(在本例中为google.com)并设置CURL的选项,以便在下载页面时它还会创建一个cookie文件。然后使用上述函数分析该文件以查看其中存在哪些cookie。
//从中提取cookie的URL
$url = 'http://www.google.com/';
//创建一个cookiefar文件
$cookiefile = tempnam("/tmp", "CURLCOOKIE");
//创建一个新的cURL资源
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//设置用户代理
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090910 Ubuntu/9.04 (jaunty) Shiretoko/3.5.3");
//设置URL和其他适当的选项
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiefile);
$data = curl_exec($curl);
//关闭cURL资源,释放系统资源
curl_close($curl);
//提取并存储找到的任何cookie
print_r(extractCookies(file_get_contents($cookiefile)));运行时,此函数会产生以下输出。
Array
(
[0] => Array
(
[domain] => .google.com
[flag] => TRUE
[path] => /
[secure] => FALSE
[expiration] => 2013-06-29 10:00:01
[name] => PREF
[value] => ID=051f529ee8937fc5:FF=0:TM=1309424401:LM=1309424401:S=4rhYyPL_bW9KxVHI
)
)