由表单提交创建的PHP会话变量不持久


PHP Session Variable created by Form Submission not persisting

我在XP上安装了Opera 12.15,在XAMPP和localhost上启用了cookie。没有。htaccess.

1)我不明白为什么下面的会话变量不坚持在Opera,而它在其他主流浏览器。仅在Opera中,如果在窗体被接受后重新访问页面(通过链接),会话变量已经消失,窗体再次显示。如果我只是刷新页面,没关系(即变量持续存在)。

2)我还有一个次要问题,正如你在下面看到的,我打开了一个php标签,开始了一个'if'语句,然后关闭了php标签,输入了一些html,打开了一个新的php标签,关闭了'if',最后关闭了第二个php标签。这是有效的代码,我最初被教导在'if'内回声html,只是有一组php标签?前者更简单,也更有效,我在其他地方看到过。

提前感谢。

<?php
// Turn on error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">   
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Opera Session Variable</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
// create a test variable to confirm other session variables outside of Form are   persisting
$_SESSION['test'] = 'Test';
// function to print session variables
function print_array( $_SESSION )
{
echo '<pre>$_SESSION<br />' . "'n";
print_r($_SESSION);
echo "</pre>'n";
}   
// process the submitted form
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if (isset($_POST['formaccept'])) {
$_SESSION['formaccepted'] = $_POST['formaccept'];
}
}
// print the session variables
print_array( $_SESSION );
// only display the form if it has not previously been accepted in this session
if (!isset($_SESSION['formaccepted'])) {
?>
<p><b>This parargraph should only display if the form has not been accepted in the current session.</b></p>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" name="formaccept" value="Accept" />
</form>
<?php
}
?>
</body>
</html>

一定是opera处理缓存的方式,我看不出你的代码有任何错误。

至于你的第二个问题,这种语法是有效的,但通常不推荐,因为它使布局变得肮脏,充满了代码片段。