Outputting getcookie variable in PHP without browser refresh
I am using the following code to output a block of content without a cookie, and another number if the cookie has been set. Problem is that the getcookie
variable doesn't work until the p开发者_开发问答age has been refreshed, or the user navigates to the next page.
I am happy to use the header redirect but not sure where to put it within this code (unless someone has a better solution to the code itself):
if (is_page(817)) {
setcookie("phonecookie", 1, time()+3600, COOKIEPATH, COOKIE_DOMAIN);
}
if ($_COOKIE["phonecookie"] =="") {
echo "no cookie here";
} else {
echo "cookie stored!";
}
Also, the code above sets the cookie if the visitor lands on a specific page within WordPress.
Is there another way to do it via query string e.g. example.com/?src=affiliate
Try this
if ((is_page(817) && (!isset($_COOKIE["phonecookie"]) {
setcookie("phonecookie", 1, time()+3600, COOKIEPATH, COOKIE_DOMAIN);
//Your redirect code here
header("Location:yoururl);
} elseif (isset($_COOKIE["phonecookie"])) {
echo "cookie stored!";
} else {
echo "no cookie here or page is not 817";
}
Using the header to redirect back to the same page:
if (is_page(817) && empty($_GET['redirect'])) {
setcookie("phonecookie", 1, time()+3600, COOKIEPATH, COOKIE_DOMAIN);
header("Location: http://url-for-this-page.com/path/?query=thequery&redirect=1");
exit(0);
}
redirect=1
has been added to the url to stop an infinite loop if the user has cookies disabled.
精彩评论