php PHP读取cookie文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/410109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP reading a cookie file
提问by Majid Fouladpour
Are there any helper libs to read a cookie file in php. I have a cookie file on my local disk and I would like a better way of reading it. I am currently just reading to file like by line and parsing out the values.
是否有任何帮助库可以读取 php.ini 中的 cookie 文件?我的本地磁盘上有一个 cookie 文件,我想要一种更好的读取方式。我目前只是按行读取文件并解析值。
回答by Majid Fouladpour
This is pretty simple if you aim to read Netscape's format (e.g. curl saves cookies in COOKIEJAR in this format).
如果您打算阅读 Netscape 的格式(例如 curl 以这种格式将 cookie 保存在 COOKIEJAR 中),这非常简单。
First an example (pipes and line numbers are added here and do not occur in real file):
首先是一个例子(管道和行号在这里添加并且不会出现在真实文件中):
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 |
As you can see:
如你看到的:
- We might have comment lines denoted with
#as the first character. - We might have blank lines
- 我们可能将注释行标记
#为第一个字符。 - 我们可能有空行
And then, the beefy lines each have 7 tokens separated with a tab character (\t).
These are defined here:
然后,每行都有 7 个标记,用制表符 ( \t)分隔。这些在这里定义:
- 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.
- domain - 创建 AND 的域,可以读取变量。
- 标志 - 一个 TRUE/FALSE 值,指示给定域中的所有机器是否都可以访问该变量。该值由浏览器自动设置,具体取决于您为域设置的值。
- path - 域内变量有效的路径。
- 安全 - 一个 TRUE/FALSE 值,指示是否需要与域的安全连接来访问变量。
- 到期 - 变量将到期的 UNIX 时间。UNIX 时间定义为自 1970 年 1 月 1 日 00:00:00 GMT 以来的秒数。
- name - 变量的名称。
- value - 变量的值。
So, now let's make our cookie-file parser.
所以,现在让我们制作我们的 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>';
Finally, hereis a demo.
最后,这是一个演示。
回答by aka
I could not find a code to cater for HttpOnlycookie records which is quite popular now - for example used in http://www.google.com/. An HttpOnly cookie is ONLY readable by browser and will remain hidden from all client side scripts like java scripts. You can find more details about HttpOnly cookies here.
我找不到适合现在非常流行的HttpOnlycookie 记录的代码- 例如在http://www.google.com/ 中使用。HttpOnly cookie 只能被浏览器读取,并且对所有客户端脚本(如 Java 脚本)都是隐藏的。您可以在此处找到有关 HttpOnly cookie 的更多详细信息。
Ignoring the format of these cookies in Netscape cookie files, will result in incorrect parsing. These records are prefixed with a "#HttpOnly_" string.
忽略 Netscape cookie 文件中这些 cookie 的格式,将导致解析错误。这些记录以“#HttpOnly_”字符串为前缀。
We should also "urldecode" parameter names and their values for almost all applications.
我们还应该为几乎所有应用程序“urldecode”参数名称及其值。
The following function is a combined and updated version of sample codes of Majid Fouladpourand Philip Nortonwhich considers HttpOnly cookies and returns all cookies with their attributes in an array:
以下函数是Majid Fouladpour和Philip Norton示例代码的组合和更新版本,它考虑了 HttpOnly cookie 并在数组中返回所有 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) {
$lines = explode(PHP_EOL, $string);
foreach ($lines as $line) {
$cookie = array();
// detect httponly cookies and remove #HttpOnly prefix
if (substr($line, 0, 10) == '#HttpOnly_') {
$line = substr($line, 10);
$cookie['httponly'] = true;
} else {
$cookie['httponly'] = false;
}
// we only care for valid cookie def lines
if( strlen( $line ) > 0 && $line[0] != '#' && substr_count($line, "\t") == 6) {
// get tokens in an array
$tokens = explode("\t", $line);
// trim the tokens
$tokens = array_map('trim', $tokens);
// Extract the data
$cookie['domain'] = $tokens[0]; // The domain that created AND can read the variable.
$cookie['flag'] = $tokens[1]; // A TRUE/FALSE value indicating if all machines within a given domain can access the variable.
$cookie['path'] = $tokens[2]; // The path within the domain that the variable is valid for.
$cookie['secure'] = $tokens[3]; // A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
$cookie['expiration-epoch'] = $tokens[4]; // The UNIX time that the variable will expire on.
$cookie['name'] = urldecode($tokens[5]); // The name of the variable.
$cookie['value'] = urldecode($tokens[6]); // The value of the variable.
// Convert date to a readable format
$cookie['expiration'] = date('Y-m-d h:i:s', $tokens[4]);
// Record the cookie.
$cookies[] = $cookie;
}
}
return $cookies;
}
And this is a demonstrationof the function.
这是该功能的演示。
回答by Nabi K.A.Z.
This library allows you to manipulate (add, delete, update,...) Netscape Cookie File (eg. Cookies generated by CURL) :
该库允许您操作(添加、删除、更新...)Netscape Cookie 文件(例如,由 CURL 生成的 Cookie):
https://github.com/kegi/netscape-cookie-file-handler
https://github.com/kegi/netscape-cookie-file-handler
Simple example of reading + writing cookies:
读取 + 写入 cookie 的简单示例:
/*Open and parse the cookie file*/
$configuration = (new Configuration())->setCookieDir('cookies/');
$cookieJar = (new CookieFileHandler($configuration))->parseFile('my_cookie_file');
/*Add (and save) a cookie*/
$cookieJar->add(
(new Cookie())
->setHttpOnly(true)
->setPath('/foo')
->setSecure(true)
->setExpire(new DateTime('2020-02-20 20:20:02'))
->setName('foo')
->setValue('bar')
)->persist();
P.S. This project is great, But I do not know why at this moment, its stars are so low! ;-)
PS 这个项目很棒,但不知为何此时星数如此之低!;-)
回答by Carsten
Quick way to display:
快速显示方式:
cat sess_qe3qq1164dnggru0m1j7fpbr23 | tr ';' '\n'
回答by null
I think $_COOKIE is what your looking for.
我认为 $_COOKIE 正是您要找的。
This superglobal can be used to read cookie data... to set it you need to use setcookie()More can be found on the PHP website under $_COOKIE superglobal
这个superglobal可以用来读取cookie数据...设置它你需要使用setcookie()更多可以在PHP网站$_COOKIE superglobal下找到
回答by lpfavreau
I'm not sure I understand you correctly as it's normally pretty straightforward to set (using setcookie) and read a cookie in PHP from your scripts:
我不确定我是否正确理解您,因为setcookie从脚本中设置(使用)和读取 PHP 中的 cookie通常非常简单:
$value = $_COOKIE['mycookie'];
If you are looking for a way of reading a raw cookie directly from your filesystem, without going through a browser, you'll need to specify what format/browser they were written in. The values could have been serialized from a lot of different languages and the end-result of the file might differ from browser to browser.
如果您正在寻找一种直接从您的文件系统读取原始 cookie 的方法,而无需通过浏览器,您需要指定它们是用什么格式/浏览器编写的。这些值可能已经从许多不同的语言中序列化并且文件的最终结果可能因浏览器而异。
// Edit:
// 编辑:
More on the browser differences: for example, Mozilla has a format like thatand IE something more like that.
回答by ahc
If you are using sessions in PHP, and you are in fact trying to parse the session data on disk, you can use the unserialize()function on the contents of that file.
如果您在 PHP 中使用会话,并且您实际上是在尝试解析磁盘上的会话数据,则可以unserialize()对该文件的内容使用该函数。

