如何正确清除我的php会话数据?

时间:2013-03-19 05:37:37

标签: php session

我的php网站流程如下:

  • Page1.php有一个html表单,POST到Page2.php
  • Page2.php将所有POST数据存储到SESSION变量中,并有一个通向Page3.php的按钮
  • Page3.php有另一种形式,将其数据发布到Page4.php
  • Page4.php然后将其所有POST数据存储到SESSION变量

我的问题是,用户单击Page4.php上的后退按钮返回Page3.php并更改一些输入可能是必要的。我们确定你们都知道当他们回到Page3.php时,表单将是空白的,因为整个页面将以其默认状态重新呈现。

要解决此问题并重新显示用户以前的输入,请执行以下操作:

<input value="<?php echo $_POST["guest1Ticket"];?> " type="text"  name="guest1Ticket" id="guest1Ticket" onblur="isTicketNumber(this)"  size ="22"/>

这是重要的一部分 - <?php echo $_POST["guest1Ticket"];?>

这可行,但给我带来了另一个问题。如果用户返回到Page1.php(在收集浏览器之前)并在他们到达Page3.php时重新开始该过程,则他们上次运行的数据将被加载到表单中。

我想我需要做的是在用户访问Page1.php时清除所有sdession变量。我试着这样做:

<?php 
 session_start(); 
 session_unset(); 
 session_destroy(); 
?> 

(上面是我文件的最顶层,第一个字符前没有空格。)

当Page1.php加载时没有生成警告,但会话变量未被取消设置。当我到达Page3.php时,上次运行的数据仍然输入到表单中。

如何正确清除会话数据?

BTW 我只需要在Chrome中使用,这就是我测试的地方。

3 个答案:

答案 0 :(得分:13)

仅对不使用$ _SESSION的旧版弃用代码使用session_unset()。

请参阅session_destroy manual

示例您可以尝试查看其工作原理

session.php文件

<?php
session_start();
$_SESSION = array('session1'=>1,'session2'=>2);

echo $_SESSION['session1']; //1
$_SESSION['session1'] = 3;
echo "<pre>";
print_r($_SESSION); //session one now updated to 3
echo "</pre>";


$_SESSION = array();
if ($_SESSION['session1']) {
 echo $_SESSION['session1']; //  IS NOW EMPTY
} else {
 echo "woops... nothing found";
}
?>
<p>
<a href="destroyed.php">NOW GOING TO DESTROYED PHP<a/>
</p>

<?php
session_destroy();
?>

destroyed.php

<?php
session_start(); // calling session start first on destroyed.php

print_r($_SESSION); // prints Array ( )  
?>

答案 1 :(得分:2)

来自文档:

If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used,
use unset() to unregister a session variable, i.e. unset ($_SESSION['varname']);

并注意session_destroy:

  

session_destroy会销毁与当前会话关联的所有数据。它不会取消设置与会话相关的任何全局变量

答案 2 :(得分:0)

使用session_unset()。像这样:

<?php session_start(); ?><!DOCTYPE html>
<html>
  <body>
    <?php
      $_SESSION["variabletounset"] = "I am going to be unset soon along with all of the other session variables.";
      print '<pre>' . "\n";
      print_r($_SESSION);
      print '    </pre>' . "\n";

      session_unset();

      print '    <pre>' . "\n";
      print_r($_SESSION);
      print '    </pre>' . "\n";
    ?>
  </body>
</html>

这将输出:

Array
(
variabletounset => I am going to be unset soon along with all of the other session variables.
)

Array
(
)