search
HomeBackend DevelopmentPHP TutorialPHP implements the function of remembering passwords and automatically logging in

  1. //Check whether the user is logged in
  2. function checklogin(){
  3. if(emptyempty($_SESSION['user_info'])){ //Check whether the session is empty
  4. if(emptyempty ($_COOKIE['username']) || emptyempty($_COOKIE['password'])){ //If the session is empty and the user does not choose to record the login status
  5. header("location:login.php?req_url=" .$_SERVER['REQUEST_URI']); //Go to the login page, record the requested url, jump to it after logging in, and have a good user experience.
  6. }else{ //The user has chosen to remember the login status
  7. $user = getUserInfo($_COOKIE['username'],$_COOKIE['password']); //Get the user's personal information
  8. if(emptyempty($ user)){ //The username and password are incorrect and the information is not available. Go to the login page
  9. header(”location:login.php?req_url=”.$_SERVER['REQUEST_URI']);
  10. }else{
  11. $_SESSION ['user_info'] = $user; //If the username and password are correct, put the user's personal information into the session
  12. }
  13. }
  14. }
  15. }
Copy code

Instructions: When accessing every page in the background, you must first perform the above checks

2. User submits login information When the user fills in the username and password, it is submitted here.

  1. /**

  2. Detection of login information submitted by users
  3. link: http://bbs.it-home.org
  4. */
  5. $username = trim($_POST['username']);
  6. $password = md5(trim($_POST[ 'password']));
  7. $validatecode = $_POST['validateCode'];
  8. $ref_url = $_GET['req_url'];
  9. $remember = $_POST['remember'];
  10. < ;p>$err_msg = ”;
  11. if($validatecode!=$_SESSION['checksum']){
  12. $err_msg = “Verification code is incorrect”;
  13. }elseif($username==” || $password== ”){
  14. $err_msg = “Neither username nor password can be empty”;
  15. }else{
  16. $row = getUserInfo($username,$password);
  17. if(emptyempty($row )){

  18. $err_msg = "Both the username and password are incorrect";
  19. }else{
  20. $_SESSION['user_info'] = $row;
  21. if(!emptyempty($remember)){ //If the user chooses, To record the login status, put the username and encrypted password in the cookie
  22. setcookie("username", $username, time()+3600*24*365);
  23. setcookie("password", $password, time() +3600*24*365);
  24. }
  25. if(strpos($ref_url,"login.php") === false){
  26. header("location:".$ref_url);
  27. }else{
  28. header(" location:main_user.php”);
  29. }
  30. }
  31. }
  32. $username = trim($_POST['username']);
  33. $password = md5(trim($_POST['password']));
  34. $validatecode = $_POST['validateCode'];
  35. $ref_url = $_GET['req_url'];
  36. $remember = $_POST['remember'];
  37. $err_msg = ”;

  38. if ($validatecode!=$_SESSION['checksum']){
  39. $err_msg = "Verification code is incorrect";
  40. }elseif($username==" || $password=="){
  41. $err_msg = "Username and The password cannot be empty";
  42. }else{
  43. $row = getUserInfo($username,$password);
  44. if(empty($row)){

  45. $err_msg = "Username and The passwords are not correct";
  46. }else{
  47. $_SESSION['user_info'] = $row;
  48. if(!empty($remember)){ //If the user chooses, the username and password will be recorded and the login status will be recorded Put the password in the cookie
  49. setcookie("username", $username, time()+3600*24*365);
  50. setcookie("password", $password, time()+3600*24*365);
  51. }
  52. if(strpos($ref_url,"login.php") === false){
  53. header("location:".$ref_url);
  54. }else{
  55. header("location:main_user.php");
  56. }
  57. }
  58. }
Copy code

Explanation about $ref_url: Suppose: User A accesses b.php, but User A is not logged in, jumps to the login page login.php, fills in the user and password on the login page, and then jumps to the page b.php after confirmation, instead of jumping A default page main_user.php. Because b.php is the page that user A wants to access, the user experience will be better.

3. When the user logs out, clear the record login status When the user clicks to log out, be sure to clear the current login status to prevent malicious people from using your login information to cause damage.

  1. //Log out
  2. function logout(){
  3. unset($_SESSION['user_info']);
  4. if(!emptyempty($_COOKIE['username']) || emptyempty ($_COOKIE['password'])){
  5. setcookie("username", null, time()-3600*24*365);
  6. setcookie("password", null, time()-3600*24*365) ;
  7. }
  8. }
  9. ?>
Copy code

Okay, I’ve introduced the method of remembering passwords and automatically logging in using php. I hope you gain something. Scripting School is dedicated to you.



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)