在 php.ini 中是否有任何帮助库来读取 cookie 文件?我的本地磁盘上有一个 cookie 文件,我想要一种更好的读取方式。我目前只是按行读取文件并解析值。
最佳答案
如果您打算读取 Netscape 的格式(例如,curl 以这种格式将 cookie 保存在 COOKIEJAR 中),这将非常简单。
首先是一个例子(管道和行号在这里添加,不会出现在真实文件中):
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 值,指示是否需要与域的安全连接才能访问变量。
- expiration - 变量到期的 UNIX 时间。 UNIX 时间定义为自格林威治标准时间 1970 年 1 月 1 日 00:00:00 以来的秒数。
- 名称 - 变量的名称。
- value - 变量的值。
那么,现在让我们来制作我们的 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是一个演示。
关于PHP 读取 cookie 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/410109/