持续当前会话无论页面重新加载

时间:2012-04-17 01:18:51

标签: php session persistence refresh

所以我有index.php (root)用户提交表单,它会在页面加载时重新生成session_id并存储在隐藏输入中。

root index.php文件中输入数据后,会将其发送到profile page,其中包含:{/ p>

session_start(); // Bring in old sessionID
$sess_id = session_id();

// If no sessionID redirect back home.
if(empty($sess_id)) {
  header('Location: ../index.php');   
}

// If don't enter, then reload page, redirect back home
elseif(empty($_POST['firstNm']) || empty($_POST['lastNm'])) {
  header('Location: ../index.php');   
}

// If sessionID first send off this data inputted from ../index.php then regenerate session id and update db
else {  
  // Connect to db
  $_SERVER['DOCUMENT_ROOT'] = 'SiteRoot/';
  // Grabs a new user's : username, pass, email from default [index.php] once submitted
  require_once($_SERVER['DOCUMENT_ROOT'].'cfg/'.'dbi.php');
  require_once($_SERVER['DOCUMENT_ROOT'].'registration/'.'inituserCredentialsGrab.php');

  // After submitting original values, update new session ID in database since original was viewable via source hidden inputs
  require_once($_SERVER['DOCUMENT_ROOT'].'registration/'.'newUserSessIDInitReg.php');
}

此文件基本上获取所有初始输入。获取通过查看源可见的初始session_id并重新生成它。重新生成后,它将提交给db。

问题是,如果我转到RELOAD页面,它似乎再次重新生成id。我如何解决这个问题,这样无论我在当前浏览器会话期间刷新了多少次,它都不会执行regenerate_id

1 个答案:

答案 0 :(得分:0)

我会在新会话中存储一个已经重新生成id的标志,并在进入页面时检查它。

例如:

session_start(); // Bring in old sessionID              
$sess_id = session_id();              

// If no sessionID redirect back home.              
if(empty($sess_id)) {              
  header('Location: ../index.php');                 
}              

// If don't enter, then reload page, redirect back home              
elseif(empty($_POST['firstNm']) || empty($_POST['lastNm'])) {              
  header('Location: ../index.php');                 
}              

// If sessionID first send off this data inputted from ../index.php then regenerate session id and update db              
elseif(!isset($_SESSION['already_stored'])){                
  // Connect to db              
  $_SERVER['DOCUMENT_ROOT'] = 'SiteRoot/';              
  // Grabs a new user's : username, pass, email from default [index.php] once submitted              
  require_once($_SERVER['DOCUMENT_ROOT'].'cfg/'.'dbi.php');              
  require_once($_SERVER['DOCUMENT_ROOT'].'registration/'.'inituserCredentialsGrab.php');              

  // After submitting original values, update new session ID in database since original was viewable via source hidden inputs              
  require_once($_SERVER['DOCUMENT_ROOT'].'registration/'.'newUserSessIDInitReg.php');
  $_SESSION['already_stored'] = true;
}

如果更新数据库的代码仍然需要在每次重新加载时运行,那么您可以将if条件移动到仅包围会话ID本身的重新生成。