Example of remembering password and automatically logging in next time in php

  • 2021-07-24 10:33:32
  • OfStack

When doing a website, you often encounter the need to remember your password, log in automatically next time, avoid logging in within 1 week, and avoid logging in within 1 month. This function is generally realized through cookie. This article will briefly explain how to use php to realize this requirement in 1. Of course, there are many ways to realize this requirement in N.

The whole process is that when the user logs in, if the option such as remembering password or avoiding login within one week is selected, after the successful login operation of the user is completed, the data of cookie realizing automatic login is stored in the user table of the database for verification during the next automatic login. If you pass the verification, you will log in automatically; Otherwise, you need to enter your user name and password to log in. The saved cookie value can take 1 random code.

The specific example code is as follows:


$username=trim($_POST['username']);
$password=md5(trim($_POST['password']));
$ref_url=$_GET['req_url'];
$remember=$_POST['remember'];// Automatic login flag
$err_msg='';
if($username==''||$password==''){
 $err_msg=" Neither user name nor password can be empty ";
}else{
 $row=getUserInfo($username,$password);
 if(empty($row)){
  $err_msg=" User name and password are incorrect ";
 }else{
  $_SESSION['user_info']=$row;
  if(!empty($remember)){// If the user chooses, record the login status and put the user name and encrypted password in cookie Inside
   setcookie("username",$username,time()+3600*24*365);
   setcookie("password",$password,time()+3600*24*365);
  }
  if(strpos($ref_url,"login.php")===false){
   header("location:".$ref_url);
  }else{
   header("location:main_user.php");
  }
 }
}

In addition, when visiting every page of the website, you should check the following functions once first.


// Check whether the user is logged in
function checklogin(){
 if(empty($_SESSION['user_info'])){// Check 1 Under session Is it empty
  if(empty($_COOKIE['username'])||empty($_COOKIE['password'])){// If session Is empty and the user did not select to record login
   header("location:login.php?req_url=".$_SERVER['REQUEST_URI']);// Go to the login page and record the requested url After logging in, jump to the past, and the user experience is good.
  }else{// The user chose to remember login status
   $user=getUserInfo($_COOKIE['username'],$_COOKIE['password']);// To get the user's personal data
  if(empty($user)){// The user name and password are incorrect. If you can't get the information, go to the login page
   header("location:login.php?req_url=".$_SERVER['REQUEST_URI']);
  }else{
   $_SESSION['user_info']=$user;// The user name and password are correct. Put the user's personal data in session Inside
  }
  }
 }
}


Related articles: