[英]Redirecting if Login Session Expires in php
I am trying to log out when session time expires. 我正在尝试在会话时间到期时注销。 I used this code: 我使用以下代码:
home.php home.php
session_start();
require_once 'class.user.php';
$user_home = new USER();
if($user_home->isLoginSessionExpired()) {
header("Location:logout.php?session_expired=1");
}
if(!$user_home->is_logged_in())
{
$user_home->redirect($web);
}
class.user.php class.user.php
public function isLoginSessionExpired() {
$login_session_duration = 10;
$current_time = time();
if(isset($_SESSION['loggedin_time']) and isset($_SESSION["userSession"])){
if(((time() - $_SESSION['loggedin_time']) > $login_session_duration)){
return true;
}
}
return false;
}
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}public function logout()
{
session_destroy();
$_SESSION['userSession'] = false;
}public function login($uname,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_users WHERE userName=:username");
$stmt->execute(array(":username"=>$uname));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['userPass']==md5($upass))
{
$_SESSION['userSession'] = $userRow['userID'];
$_SESSION['user_name'] = $userRow['userName'];
return true;
}
else
{
header("Location: index.php?error");
exit;
}
}
else
{
header("Location: index.php?inactive");
exit;
}
}
else
{
header("Location: index.php?error");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
logout.php logout.php
<?php
session_start();
require_once 'class.user.php';
$user = new USER();
if(!$user->is_logged_in())
{
$user->redirect($web);
}
if($user->is_logged_in()!="")
{
$user->logout();
$user->redirect($web);
}
$url = $web;
if(isset($_GET["session_expired"])) {
$url .= "?session_expired=" . $_GET["session_expired"];
}
header("Location:$url");
?>
login.php 的login.php
<?php
session_start();
require_once 'class.user.php';
$user_login = new USER();
if($user_login->is_logged_in()!="")
{
$user_login->redirect($web.$_SESSION['user_name']);
}
if(isset($_POST['btn-login']))
{
$uname = trim($_POST['txtuname']);
$upass = trim($_POST['txtupass']);
if($user_login->login($uname,$upass))
{
$user_login->redirect($uname);
}
}
?>
But my code is not working! 但是我的代码不起作用! How can I sort out my problem? 如何解决我的问题?
The problem in User
's logout()
method. User
的logout()
方法中的问题。
Since if you do $_SESSION['userSession'] = false;
因为如果您这样做$_SESSION['userSession'] = false;
the isset($_SESSION["userSession"])
will still give you true
. isset($_SESSION["userSession"])
仍然会为您提供true
。 So in class.user.php it should be: 所以在class.user.php中,它应该是:
public function logout(){
session_destroy();
unset($_SESSION['userSession']);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.