irwan

How to Use Cookies in PHP (Basic)

Apr 20th, 2012
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.03 KB | None | 0 0
  1. <?php
  2. if (!isset($_POST['email'])) {
  3. // if form has not been submitted
  4. // display form
  5. // if cookie already exists, pre-fill form field with cookie value
  6. ?>
  7. <html>
  8. <head></head>
  9. <body>
  10.  
  11. <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
  12. Enter your email address: <input type="text" name="email" value="<?php echo $_COOKIE['email'] ?>" size="20">
  13. <input type="submit" name="submit">
  14. <?php
  15. // also calculate the time since the last submission
  16. if ($_COOKIE['lastsave']) {
  17. $days = round((time() - $_COOKIE['lastsave']) / 86400)
  18. echo " $days day(s) since last submission"
  19. }
  20. ?>
  21. </form>
  22.  
  23. </body>
  24. </html>
  25. <?php
  26. }
  27. else {
  28. // if form has been submitted
  29. // set cookies with form value and timestamp
  30. // both cookies expire after 30 days
  31. if (!empty($_POST['email'])) {
  32. setcookie("email", $_POST['email'], mktime()+(86400*30), "/")
  33. setcookie("lastsave", time(), mktime()+(86400*30), "/")
  34. echo "Your email address has been recorded."
  35. }
  36. else {
  37. echo "ERROR: Please enter your email address!"
  38. }
  39. }
  40. ?>
  41. </body>
  42. </html>
Advertisement
Add Comment
Please, Sign In to add comment