Reputation:
i want to use cookie
in web page and i want to use it for save any optional variables. but after use setcookie
and refresh page isset()
could not detect, i must be many refresh page for use it,
i cant use it in first refresh or visit page.
PHP:
setcookie("user", "Alex Porter", time()+3600);
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else
echo "Welcome guest!<br>";
//unset($_COOKIE['user']);
//setcookie('user', '', time() - 3600);
RESULT:
after save and refresh page
Welcome guest!
second refresh :
Welcome Alex Porter
Upvotes: 7
Views: 19383
Reputation: 6701
Well, there is nothing wrong in this. The first time you refresh, you actually run the script to set the cookie. So, it executes the else statement.
When you refresh it the second time, the isset()
function returns true and the if statement gets executed.
Here is a pictorial description:
However, there is a problem with your script. Refreshing your page everytime updates the cookie time to 3600 seconds
. So, you need to set the cookie only when there is no cookie set on the user's browser like this:
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else
{
echo "Welcome guest!<br>";
setcookie("user", "Alex Porter", time()+3600);
}
Upvotes: 6
Reputation: 2635
The $_COOKIE
data is read from the client's request data, and is not written immediately by setCookie()
. This is normal behavior and should be incorporated into your program flow.
If you want the cookie data to be immediately available in your case, you might try something like this:
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else {
$user = "Alex Porter";
setcookie("user", $user, time()+3600);
echo "Welcome $user!<br>";
}
Upvotes: 1
Reputation: 4884
When you set a cookie, it is sent to the browser. The next time the browser then sends a request for a page, it sends the cookie information back and the page can make use of it.
To fix it, redirect the user to the page where you want to display the data after the cookie has been set, instead of simply displaying the page. This way you can make use of the cookie data.
Upvotes: 10
Reputation: 20286
Cookie is set to a specific path and domain. You should change setcookie() to
setcookie ("user", "Alex Porter", time()+3600, "/", "youdomain.com");
If set to '/', the cookie will be available within the entire domain(youdomain.com).
Cookie will be visible after page refresh.
Your code can be simplifed as well:
echo "Welcome " . isset($_COOKIE["user"]) ? $_COOKIE["user"] : "guest" . "!<br>";
Upvotes: 1
Reputation: 158100
I guess you want something like this:
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else {
echo "Welcome guest!<br>";
setcookie("user", "Alex Porter", time()+3600);
}
Upvotes: 0