cookie 中的数组 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9032007/
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
Arrays in cookies PHP
提问by Paul Barrios
How is proper way to store an array in a cookie? in PHP Code example:
在 cookie 中存储数组的正确方法是什么?在 PHP 代码示例中:
$number_ticket=2;
$info[7][5]=1;
$info[8][5]=1;
回答by Marty Aghajanyan
To store the array values in cookie, first you need to convert them to string, so here is some options.
要将数组值存储在 cookie 中,首先需要将它们转换为字符串,因此这里有一些选项。
Storing cookies as JSON
将 cookie 存储为 JSON
Storing code
存储代码
setcookie('your_cookie_name', json_encode($info), time()+3600);
Reading code
读码
$data = json_decode($_COOKIE['your_cookie_name'], true);
JSON can be good choose also if you need read cookie in front end with JavaScript.
如果您需要使用 JavaScript 在前端读取 cookie,JSON 也是不错的选择。
Actually you can use any encrypt_array_to_string
/decrypt_array_from_string
methods group that will convert array to string and convert string back to samearray.
For example you can also use explode
/implode
for array of integers.
实际上,您可以使用任何encrypt_array_to_string
/decrypt_array_from_string
方法组将数组转换为字符串并将字符串转换回相同的数组。例如,您还可以将explode
/implode
用于整数数组。
Warning: Do not use serialize/unserialize
警告:不要使用序列化/反序列化
From PHP.net
来自 PHP.net
Do not pass untrusted user input to unserialize().
- Anything that coming by HTTP including cookies is untrusted!
Do not pass untrusted user input to unserialize().
- 任何通过 HTTP 包括 cookie 的内容都是不可信的!
References related to security
安全相关参考
- http://php.net/manual/en/function.unserialize.php#refsect1-function.unserialize-notes
- https://www.owasp.org/index.php/PHP_Object_Injection
- https://websec.files.wordpress.com/2010/11/rips_ccs.pdf
- https://www.notsosecure.com/remote-code-execution-via-php-unserialize/
- https://www.alertlogic.com/blog/writing-exploits-for-exotic-bug-classes-unserialize()/
- https://hakre.wordpress.com/2013/02/10/php-autoload-invalid-classname-injection/
- https://security.stackexchange.com/questions/77549/is-php-unserialize-exploitable-without-any-interesting-methods
- http://php.net/manual/en/function.unserialize.php#refsect1-function.unserialize-notes
- https://www.owasp.org/index.php/PHP_Object_Injection
- https://websec.files.wordpress.com/2010/11/rips_ccs.pdf
- https://www.notsosecure.com/remote-code-execution-via-php-unserialize/
- https://www.alertlogic.com/blog/writing-exploits-for-exotic-bug-classes-unserialize()/
- https://hakre.wordpress.com/2013/02/10/php-autoload-invalid-classname-injection/
- https://security.stackexchange.com/questions/77549/is-php-unserialize-exploitable-without-any-interesting-methods
As an alternative solution, you can do it also without converting array to string.
作为替代解决方案,您也可以在不将数组转换为字符串的情况下执行此操作。
setcookie('my_array[0]', 'value1' , time()+3600);
setcookie('my_array[1]', 'value2' , time()+3600);
setcookie('my_array[2]', 'value3' , time()+3600);
And after if you will print $_COOKIE
variable, you will see the following
之后,如果您将打印$_COOKIE
变量,您将看到以下内容
echo '<pre>';
print_r( $_COOKIE );
die();
Array ( [my_array] => Array ( [0] => value1 [1] => value2 [2] => value3 ) )
This is documented PHP feature.
这是记录在案的 PHP 功能。
From PHP.net
来自 PHP.net
Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.
Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.
回答by Narcis Radu
Serialize data:
序列化数据:
setcookie('cookie', serialize($info), time()+3600);
Then unserialize data:
然后反序列化数据:
$data = unserialize($_COOKIE['cookie'], ["allowed_classes" => false]);
After data, $info and $data will have the same content.
在 data 之后, $info 和 $data 将具有相同的内容。
回答by Nathan
Using serialize and unserialize on cookies is a security risk. Users (or attackers) can alter cookie data, then when you unserialize it, it could run PHP code on your server. Cookie data should not be trusted. Use JSON instead!
在 cookie 上使用序列化和反序列化存在安全风险。用户(或攻击者)可以更改 cookie 数据,然后当您对其进行反序列化时,它可以在您的服务器上运行 PHP 代码。不应信任 Cookie 数据。请改用 JSON!
From PHP's site:
从PHP 的网站:
Do not pass untrusted user input to
unserialize()
regardless of theoptions
value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (viajson_decode()
andjson_encode()
) if you need to pass serialized data to the user.
unserialize()
无论allowed_classes的options
值如何,都不要将不受信任的用户输入传递给。由于对象实例化和自动加载,反序列化可能导致代码被加载和执行,恶意用户可能能够利用这一点。如果需要将序列化数据传递给用户,请使用安全、标准的数据交换格式,例如 JSON(通过和)。json_decode()
json_encode()
回答by Rob Agar
Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode
). Be aware that there is a limit on the length of the string you can store though.
Cookie 基本上是文本,因此您可以通过将数组编码为 JSON 字符串来存储数组(请参阅 参考资料json_encode
)。请注意,您可以存储的字符串长度是有限制的。
回答by Dunhamzzz
Try serialize()
. It converts an array into a string format, you can then use unserialize()
to convert it back to an array. Scripts like WordPress use this to save multiple values to a single database field.
试试serialize()
。它将数组转换为字符串格式,然后您可以使用unserialize()
将其转换回数组。像 WordPress 这样的脚本使用它来将多个值保存到单个数据库字段。
You can also use json_encode()
as Rob said, which maybe useful if you want to read the cookie in javascript.
您也可以json_encode()
像 Rob 所说的那样使用,如果您想在 javascript 中读取 cookie,这可能很有用。
回答by Elzo Valugi
You can also try to write different elements in different cookies. Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes. Look at setcookiePHP function for more details
您也可以尝试在不同的 cookie 中编写不同的元素。Cookie 名称可以设置为数组名称,并且可以作为数组供您的 PHP 脚本使用,但单独的 Cookie 存储在用户系统上。考虑explode() 设置一个具有多个名称和值的cookie。不建议为此目的使用 serialize(),因为它会导致安全漏洞。查看setcookiePHP 函数以获取更多详细信息
回答by V? Minh
Just found the thing needed. Now, I can store products visited on cookies and show them later when they get back to the site.
刚找到需要的东西。现在,我可以在 cookie 上存储访问过的产品,并在他们返回站点时显示它们。
// set the cookies
setcookie("product[cookiethree]", "cookiethree");
setcookie("product[cookietwo]", "cookietwo");
setcookie("product[cookieone]", "cookieone");
// after the page reloads, print them out
if (isset($_COOKIE['product'])) {
foreach ($_COOKIE['product'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
回答by Shakeel Memon
recently i've created this code for my client, i'm using array for cookie in this code, actually this code gets recently viewed pages by user using cookies, hope it helps you...!
最近我为我的客户创建了这段代码,我在这段代码中使用了 cookie 数组,实际上这段代码使用 cookie 获取用户最近查看的页面,希望它对你有帮助......!
function curPageURL() { // get url
return 'http' . ((
!empty($_SERVER['HTTPS']) &&
$_SERVER['HTTPS'] !== 'off' ||
$_SERVER['SERVER_PORT'] == 443
) ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . (
$_SERVER['SERVER_PORT'] == 80 ? '' : $_SERVER['SERVER_PORT']
) . $_SERVER['REQUEST_URI'];
}
$currentPage = curPageURL(); // call function
$counter = $_COOKIE['_counter']; // set counter variable
if(!$_COOKIE['_PAGES']){ // if _Pages cookie
$default = 1; // set default value to 1
setcookie("_counter",$default,time()+7200); // set counter cookie
setcookie("_PAGES[$default]",$currentPage, time()+3600); // set cookie
}
else{ // if ! _Pages cookie
$default = $counter+1; // set default value to +1
setcookie("_counter",$default,time()+7200); // set counter cookie
}
if(@in_array($currentPage, @$_COOKIE['_PAGES'])){ // if same url found
}
else{ // if new url found
setcookie("_PAGES[$default]",$currentPage, time()+3600); // set cookie
}
if($_COOKIE['_PAGES']){
foreach ($_COOKIE['_PAGES'] as $value){
echo "<a href='{$value}'>{$value}</a>";
}
}