我已经完成了我的表单,我知道如何使用 PHP 设置单个 cookie,但是设置 cookie 字符串的最佳格式是什么。我想要一个像这样的cookie(或类似的,我的格式只是一个例子);
首选项[主题=这个&布局=那个]
我如何像这样设置 cookie,然后从我的字符串中获取信息?
到目前为止的代码:
<?php
if (isset($_POST['submitted'])) {
$a = gmdate("M d Y H:i:s");
$b = "Cookies=true&Cookies_Accepted=" . $a . "";
$c = $_POST["APT_SELECTED"];
$d = $_POST["APPT_SELECTED"];
if ($d == 'Custom') {
$d = $c;
};
$e = $_POST["APL_SELECTED"];
$f = $_POST["APTNP_SELECTED"];
$g = $_POST["APSNP_SELECTED"];
$h = $_POST["APSNM_SELECTED"];
$i = $_POST["ScreenTimeout"];
$j = time() + (10 * 365 * 24 * 60 * 60);
$k = "/admin/";
$l = "rafflebananza.com";
$m = array(
'APCA' => 'true',
'APCAW' => $a,
'APT' => $c,
'APPT' => $d,
'APL' => $e,
'APTNP' => $f,
'APSNP' => $g,
'APSNM' => $h,
'APLSA' => $i
);
foreach ($m as $n => $o) {
setcookie("RBAP_Prefs[$n]", $o, $j, $k, $l);
};
header("Location: http://admin.rafflebananza.com/incex.php");
};
?>
最佳答案
PHP 将允许您在 setcookie()
中使用 []
表示法设置字符串值,您可以多次调用 setcookie()
使用您的两个子键,并将 Prefs
作为名称。
从技术上讲,PHP 将为数组元素设置多个 cookie,但是当从 $_COOKIE
读回时,PHP 会按照您期望读取数组的方式准确排列它。
所以你可以将其设置为:
// And set each in the cookie 'Prefs'
setcookie('Prefs[theme]', 'this' /*, $timeout, $path, $domain... */);
setcookie('Prefs[layout]', 'that' /*, $timeout, $path, $domain... */);
并且它可以作为 $_COOKIE['Prefs']
中的数组读取
print_r($_COOKIE['Prefs']);
// Array (
// [theme] => this,
// [layout] => that
// )
您可以循环遍历现有数组,而不是为每个数组手动调用 setcookie()
。如果您只有一层嵌套,这会很方便。
// Define your array
$prefs = array('theme' => 'this', 'layout' => 'that');
// Loop to create keys
foreach ($prefs as $key => $value) {
setcookie("Prefs[$key]", $value, $timeout, $path, $domain);
}
如果由于某种原因您必须以查询字符串样式&
分隔字符串开头,例如theme=this&layout=that
,您可以首先将其解析为数组using parse_str()
.
parse_str('theme=this&layout=that', $prefs);
// $prefs is now as in the previous example. Proceed to set
// cookie values with the foreach loop...
如果您决定以字符串格式存储 cookie,您可以将该字符串传递给 setcookie()
,然后使用 parse_str()
读取它退出$_COOKIE
。但我不喜欢这种方法,我宁愿看到 cookie 设置为上面的数组值。
// Set it as a string
setcookie('Prefs', 'theme=this&layout=that');
// And parse it from $_COOKIE into $prefs
parse_str($_COOKIE['Prefs'], $prefs);
More examples are available在 setcookie()
文档中。
关于PHP 设置并读取 Cookie 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28220280/