I can set a normal cookie, like only set name, value and expires. But I can't set it into secure cookie or httpOnly cookie or both.
Here is my code:
<?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.";
?>
I have searched in search engine. Try every way. Such as changing a setting in php.ini etc.
It showed no error but it still doesn't work. Please answer on my question.
The sixth argument of setcookie
ensures that the cookie will be only set for HTTPS requests. Set it to false, or be sure to connect via HTTPS.
Also, note that setcookie
won't modify $_COOKIE
, since cookies are loaded only once, before the script's execution.
If you need to get the value from the $_COOKIE
variable, you should set it manually:
setcookie("TestCookie", "CookieValue", 0, null, null, true, true);
$_COOKIE["TestCookie"] = "CookieValue";
You can also refresh the page, but that could create a redirection loop for people who have disabled cookies in their browsers:
<?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();
}
?>