PHP-使会话在X分钟后过期 [英] PHP - make session expire after X minutes
本文介绍了PHP-使会话在X分钟后过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下技术...
i am using the following technique...
从login.php
表单发布到页面check.php
,我在其中进行此操作
From the login.php
the form posts to the page check.php
where i do this
<?php
$uzer = $_POST['user_name'];
$pass = $_POST['user_pass'];
require ('DB_connection.php');
$result = mysql_query("SELECT * FROM accounts WHERE user_Name='$uzer' AND user_Pass='$pass'");
if( mysql_num_rows( $result ) > 0)
{
$array = mysql_fetch_assoc($result);
session_start();
$_SESSION['user_id'] = $uzer;
header("Location:loggedin.php");
}
else
{
header("Location:login.php");
}
?>
在loggedin.php
页面上,我要做的第一件事是
and on loggedin.php
page the first thing i do is
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) )
{
header("Location:login.php");
}
else
{
echo ( "this session is ". $_SESSION['user_id'] );
//show rest of the page and all
}
?>
但是当我直接输入网址localhost\myProject\loggedin.php
时登录后,它会显示页面...这很有意义,因为会话已开始
but once logged in when i directly type the url localhost\myProject\loggedin.php
it displays the page...which makes perfect sense because the session has started
我要实现的是
- 直接URL \会话将在会话终止\过期\超时后工作10分钟,然后使用必须再次登录,并且可能会获得相同的会话ID,但是10分钟后,使用将无法使用同一会话
我需要做什么或学习
推荐答案
在会话中存储时间戳:
<?php
$uzer = $_POST['user_name'];
$pass = $_POST['user_pass'];
require ('DB_connection.php');
// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($uzer), mysql_real_escape_string($pass));
if( mysql_num_rows( $result ) > 0)
{
$array = mysql_fetch_assoc($result);
session_start();
$_SESSION['user_id'] = $uzer;
$_SESSION['login_time'] = time();
header("Location:loggedin.php");
}
else
{
header("Location:login.php");
}
?>
检查时间戳是否在允许的时间范围内(600秒为10分钟):
Check if the timestamp is within the allowed time window (600 seconds is 10 minutes):
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 600)
{
header("Location:login.php");
}
else
{
// uncomment the next line to refresh the session, so it will expire after ten minutes of inactivity, and not 10 minutes after login
//$_SESSION['login_time'] = time();
echo ( "this session is ". $_SESSION['user_id'] );
//show rest of the page and all
}
?>
这篇关于PHP-使会话在X分钟后过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文