How to add "keep me logged in" and store the user and expiration date to MySQL database?
I want to keep the user logged in, 30 days. After 30 days, it will automatically logout.
I read some question, but I don't know how to implement it to my current login php script
How to do this? Please help me, I'm not good in PHP.
Here's my script:
session_start();
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
$loginDate = date("Y-m-d H:i:s");
$Error ="";
$successMessage ="";
if (isset($_POST['submit'])){
if ( !( $_POST['cnumber'] == "" && $_POST['password'] == "")){
$cnumber=$_POST['cnumber'];
$password= sha1($_POST['password']);
$rememberMe=$_POST['rememberme'];
$cnumber = filter_var($cnumber, FILTER_SANITIZE_NUMBER_INT);
if($rememberMe == 'checked'){
setcookie('persistID', $cnumber, time()+(30 * 24 * 60 * 60), '/'); // this sets cookie for 30 days.
}
if (filter_var($cnumber, FILTER_VALIDATE_INT)){
$con=mysqli_connect("localhost","root","","users");
$result = mysqli_query($con, "SELECT * FROM users WHERE contractNumber='$cnumber' AND password='$password'");
$data = mysqli_num_rows($result);
if(isset($_COOKIE['persistID'])){
if($data==1){
$cnumber = $_COOKIE['persistID'];
$_SESSION['login_user']=$cnumber;
mysqli_query($con, "INSERT INTO `users`.`logs`(`contractNumber`, `lastLogin`, `ipAddress`) VALUES ('$cnumber', '$loginDate', '$ipaddress')");
header('Location: profile.php');
} else {
header('Location: login.php');
} else {
$Error ="Invalid Contract Number or Password.";
}
mysqli_close($con);
} else {
$Error ="Invalid Contract Number.";
}
}
} else {
$Error ="Contract Number or Password is Empty.";
}
}
Keep a remember me checkbox in your login form. submit values to php file.
Then whenever you load your page anytime or anyday,, 1st check persistID cookie present or not. if present get uid from cookie and redirect user to home page of your website. else redirect to login page.
code to check if cookie present or not :
Hope it helps.