Using Cookies in PHP > Practical Cookies : User Logon


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. /* These are our valid username and passwords */
  3. $user = 'jonny4';
  4. $pass = 'delafoo';
  5.  
  6. if (isset($_POST['username']) && isset($_POST['password')) {
  7.  
  8. if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) {
  9.  
  10. if (isset($_POST['rememberme'])) {
  11. /* Set cookie to last 1 year */
  12. setcookie('username', $_POST['username'], time()+60*60*24*365, '/account', 'www.example.com');
  13. setcookie('password', md5($_POST['password']), time()+60*60*24*365, '/account', 'www.example.com');
  14.  
  15. } else {
  16. /* Cookie expires when browser closes */
  17. setcookie('username', $_POST['username'], false, '/account', 'www.example.com');
  18. setcookie('password', md5($_POST['password']), false, '/account', 'www.example.com');
  19. }
  20. header('Location: index.php');
  21.  
  22. } else {
  23. echo 'Username/Password Invalid';
  24. }
  25.  
  26. } else {
  27. echo 'You must supply a username and password.';
  28. }
  29. ?>
  30.  
  31. <?php
  32. /* These are our valid username and passwords */
  33. $user = 'jonny4';
  34. $pass = 'delafoo';
  35.  
  36. if (isset($_COOKIE[['username']) && isset($_COOKIE['password')) {
  37.  
  38. if (($_POST['username'] != $user) || ($_POST['password'] != md5($pass))) {
  39. header('Location: login.html');
  40. } else {
  41. echo 'Welcome back ' . $_COOKIE['username'];
  42. }
  43.  
  44. } else {
  45. header('Location: login.html');
  46. }
  47. ?>

URL: http://www.phpnerds.com/article/using-cookies-in-php/2

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.