PHP 读取 cookie 文件

标签 php cookies

在 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 |

如你所见:

  1. 我们的注释行可能以 # 作为第一个字符。
  2. 我们可能有空行

然后,每行都有 7 个标记,用制表符 (\t) 分隔。 这些定义为 here :

  1. 域 - 创建并可以读取变量的域。
  2. flag - 一个 TRUE/FALSE 值,指示给定域中的所有计算机是否都可以访问该变量。该值由浏览器自动设置,具体取决于您为域设置的值。
  3. path - 域中变量有效的路径。
  4. secure - 一个 TRUE/FALSE 值,指示是否需要与域的安全连接才能访问变量。
  5. expiration - 变量到期的 UNIX 时间。 UNIX 时间定义为自格林威治标准时间 1970 年 1 月 1 日 00:00:00 以来的秒数。
  6. 名称 - 变量的名称。
  7. 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/

相关文章:

javascript - jQuery cookie 根本不起作用

php - Laravel 按相关表排序

php - 从查询返回的表中的输入标记运行查询

javascript - Cookie 和 URL 以及实例

java - 编写cookie Java : Getting the server to set/use a cookie

javascript - Angular-cookie 错误

PHP 提交选择

php - 如何转置多维多文件上传提交并维护关联键?

php - 访问RFID的编程语言

javascript - AngularJS 中 Session Storage、Local Storage 和 Cookies 的区别