如何创建安全的 Cookie?我尝试了所有方法,但仍然不起作用


How can I create a secure cookie? I tried every thing but still not work

我可以设置一个普通的cookie,比如只设置名称,值和过期。但是我无法将其设置为安全cookie或httpOnly cookie或两者兼而有之。

这是我的代码:

<?php
setcookie("TestCookie", "CookieValue", 0, null, null, true, true);
if(isset($_COOKIE["TestCookie"])){
    echo '$_COOKIE["TestCookie"] = '.$_COOKIE['TestCookie'];
    session_id($_COOKIE["TestCookie"]);
}
else
    echo "Sorry! Cookie TestCookie was not set.";
?>

我已经在搜索引擎中搜索过。尝试各种方法。例如更改 php 中的设置.ini等。

它没有显示错误,但仍然不起作用。请回答我的问题。

setcookie的第六个参数确保 cookie 将仅针对 HTTPS 请求设置。将其设置为 false,或确保通过 HTTPS 进行连接。

另外,请注意,setcookie不会修改$_COOKIE,因为 cookie 在脚本执行之前只加载一次。

如果需要从 $_COOKIE 变量中获取值,则应手动设置它:

setcookie("TestCookie", "CookieValue", 0, null, null, true, true);
$_COOKIE["TestCookie"] = "CookieValue";

您也可以刷新页面,但这可能会为在浏览器中禁用 cookie 的用户创建重定向循环:

<?php
setcookie("TestCookie", "CookieValue", 0, null, null, true, true);
if(isset($_COOKIE["TestCookie"])){
    echo '$_COOKIE["TestCookie"] = '.$_COOKIE['TestCookie'];
    session_id($_COOKIE["TestCookie"]);
}
else{
    header('Refresh: 0');
    exit();
}
?>