如果您打算阅读 Netscape 的格式(例如,curl 以这种格式将 cookies 保存在 COOKIE JAR 中),那么这非常简单。
首先是一个示例(此处添加管道和行号,并且不会出现在实际文件中):
01 | # Netscape HTTP Cookie File
02 | # http://curl.haxx.se/rfc/cookie_spec.html
03 | # This file was generated by libcurl! Edit at your own risk.
04 |
05 | .google.com TRUE / FALSE 1305843382 cookiename the value
06 | .yahoo.com TRUE / FALSE 1305843382 another_cookie it's value
07 |
如你看到的:
- 我们可能有注释行
#
作为第一个字符。
- 我们可能有空行
然后,每行都有 7 个标记,用制表符分隔 (\t
)。
这些被定义here:
- 域 - 创建并且可以读取变量的域。
- flag - TRUE/FALSE 值,指示给定域内的所有计算机是否可以访问该变量。该值由浏览器自动设置,具体取决于您为域设置的值。
- path - 变量有效的域内的路径。
- secure - TRUE/FALSE 值,指示是否需要与域的安全连接来访问变量。
- 过期 - 变量过期的 UNIX 时间。 UNIX 时间定义为自 1970 年 1 月 1 日 00:00:00 GMT 以来的秒数。
- 名称 - 变量的名称。
- 值 - 变量的值。
那么,现在让我们来制作 cookie 文件解析器。
// read the file
$lines = file('path/to/cookies.txt');
// var to hold output
$trows = '';
// iterate over lines
foreach($lines as $line) {
// we only care for valid cookie def lines
if($line[0] != '#' && substr_count($line, "\t") == 6) {
// get tokens in an array
$tokens = explode("\t", $line);
// trim the tokens
$tokens = array_map('trim', $tokens);
// let's convert the expiration to something readable
$tokens[4] = date('Y-m-d h:i:s', $tokens[4]);
// we can do different things with the tokens, here we build a table row
$trows .= '<tr></td>' . implode('</td><td>', $tokens) . '</td></tr>' . PHP_EOL;
// another option, make arrays to do things with later,
// we'd have to define the arrays beforehand to use this
// $domains[] = $tokens[0];
// flags[] = $tokens[1];
// and so on, and so forth
}
}
// complete table and send output
// not very useful as it is almost like the original data, but then ...
echo '<table>'.PHP_EOL.'<tbody>'.PHP_EOL.$trows.'</tbody>'.PHP_EOL.'</table>';
最后,here是一个演示。