php利用cookie实现自动登录的方法

这篇文章主要介绍了php利用cookie实现自动登录的方法,涉及针对cookie的读取判断及登陆操作,是非常实用的技巧,需要的朋友可以参考下

本文实例讲述了php利用cookie实现自动登录的方法。分享给大家供大家参考。具体实现方法如下:

html前端页面代码如下:

  1. <html>
  2. <head>
  3. <title>enter password</title>
  4. </head>
  5. <body>
  6. <form name="forml" method="post" action="cookiebasedpasswordlogin.php">
  7. <table>
  8. <tr>
  9. <td colspan="2" >
  10. <div align="center"><b>please specify the password</b></div>
  11. </td>
  12. </tr>
  13. <tr>>
  14. <td>
  15. <div align="right">customer id</div>
  16. </td>
  17. <td>
  18. <input type="text" name="username">
  19. </td>
  20. </tr>
  21. <tr>
  22. <td>
  23. <div align="right">password</div>
  24. </td>
  25. <td>
  26. <input type="password" name="password">
  27. </td>
  28. </tr>
  29. <tr>
  30. <td colspan="2">
  31. <center>
  32. <input type="submit" name="submit" value="login">
  33. </center>
  34. </td>
  35. </tr>
  36. </table>
  37. </form>
  38. </body>
  39. </html>

后端PHP代码如下:

  1. <?php
  2. $now = getdate();
  3. $storetime= $now["weekday"] . " " . $now["month"] ." " . $now["year"] ;
  4. $storetime.=" time : ";
  5. if ($now["hours"] < 10) {
  6. $storetime.= "0" . $now["hours"];
  7. } else {
  8. $storetime.= $now["hours"];
  9. }
  10. $storetime.= ":";
  11. if ($now["minutes"]<10) {
  12. $storetime.= "0" . $now["minutes"];
  13. } else {
  14. $storetime.= $now["minutes"];
  15. }
  16. $storetime.= ": ";
  17. if ($now["seconds"] <10) {
  18. $storetime.= "0" . $now["seconds"];
  19. } else {
  20. $storetime.= $now["seconds"];
  21. }
  22. if (isset($data)) {
  23. $counter=++$data[l];
  24. setcookie("data[0]",$storetime,time() + (60*60*24));
  25. setcookie("data[l]", $counter,time() + (60*60*24)); setcookie("data[2]",$username,time() + (60*60*24));
  26. echo "<b><center>hi " . $data[2] . " ! !</center></b><br>n";
  27. echo "<b><center>last login time :" .$data[0] . "</center></b><br>n";
  28. echo "<b><center>current date :" .$storetime. "</center></b><br>n";
  29. echo "<b><center>page view count :" . $data[l]. "</center></b><br>n";
  30. echo "<b><center>you have successfully logged in!</center></b>";
  31. echo ("<b><contor>you can access this area without entering a password for the next 24 hours!</center></b>");
  32. } else {
  33. if (isset($username) && isset($password)) {
  34. if ($password=="superpass") {
  35. $counter=0;
  36. setcookie("data[0]",$storetime,time() + (60*60*24));
  37. setcookie("data[l]",$counter,time() + (60*60*24));
  38. setcookie("data[2]",$username,time() + (60*60*24));
  39. $url="location: cookieimp.php";
  40. header($url);
  41. }else{
  42. echo "<hl><center>invalid password!!!</center></hl>";
  43. }
  44. }
  45. }
  46. ?>

希望本文所述对大家的PHP程序设计有所帮助。