I am experimenting with cookies and i am doing this quick example,
<html>
<head>
<meta charset="UTF-8">
<title>Cookies</title>
</head>
<body>
<!-- Start of FORM -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Username: <input type="text" name="username"><br>
<input type="submit" name="submit" value="Submit">
</form>
<!-- End of FORM -->
<hr>
<?php
if (isset($_POST['username'] )) {
setcookie('username', $_POST['username'], time() + 1000, '/');
if(isset($_COOKIE['username'])){
echo "Hello " . $_COOKIE['username'];
unset($_COOKIE['username']);
}
}
?>
</body>
It works but i have to click the submit button twice for my message to display, why is that?
asked May 8, 2014 at 5:31
Daniel Sega
3333 gold badges9 silver badges19 bronze badges
1 Answer 1
From the PHP Docs..
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires.
So whilst you clicked the button the second time, the actual load was in effect and you were able to see it(the cookie).
answered May 8, 2014 at 5:33
Shankar Narayana Damodaran
68.6k43 gold badges102 silver badges129 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-php
setcookie()before you send output; it's only by luck that it works here.