首页 > 解决方案 > 不能跨页面携带 SESSION 变量

问题描述

我在使用会话变量时遇到问题。我在 page1.php 上创建了会话变量,然后尝试在 page2.php 上显示它,但它不起作用。我确保添加 session_start(); 在页面的开头,所以这不是问题。

这是我的 page1.php 代码

<?php 
session_start();

?>

<!DOCTYPE html>
<html lang="en-US">

<head>

<title>website</title>
<link rel="icon" href="icon.png">
<link rel="stylesheet" type="text/css" href="style.css">

<?php 
if(!isset($_POST["submit"])) {

$_SESSION["username"] = $_POST["username"];

}

?>


 </head>

 <body id="body">

<form action="page2.php" method="post">

<input type="username" id="username" name="username" placeholder="Username">
<input type="submit" id="submit" name="submit" value="Submit">

</form>

</body>

</html>

这是我的 page2.php 代码

<?php

 session_start();


?>

<!DOCTYPE html>
<html lang="en-US">

<head>


<title>website</title>
<link rel="icon" href="icon.png">
<link rel="stylsheet" type="text/css" href="style.css">

</head>

<body id="body">

Your username is: <?php echo $_SESSION["username"]; ?>
</body>

</html>

标签: phphtml

解决方案


$_POST['username']将不可用page1.php它只会在page2响应提交的表格的页面中可用。

同样$_POST["submit"]将不可用page1

在测试时将其添加到脚本的顶部,然后即使您正在为 LIVE 环境配置的站点上进行开发,您也会看到如下错误

应从其发送的未定义索引page1.php

<?php
ini_set('display_errors', 1); 
ini_set('log_errors',1); 
error_reporting(E_ALL); 

推荐阅读