2

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
1
  • You should call setcookie() before you send output; it's only by luck that it works here. Commented May 8, 2014 at 5:39

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.