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?
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).