PHP提交表单后Session数据丢失未设置问题求解
问题根因
- 表单提交跳转逻辑与Session赋值逻辑错位:你的s1.php中表单
action属性设置为s2.php,点击提交后浏览器会直接将请求发送到s2.php页面,s1.php底部的isset($_GET['submit'])赋值逻辑全程不会被执行,因此$_SESSION['name']从未被写入,s2.php自然读取不到对应Session值。 - 你提到非表单提交场景下Session功能正常,也佐证了该判断:当你直接在s1.php中执行Session赋值逻辑、不触发表单跳转时,赋值操作可正常完成,Session就可以跨页读取。
解决方案
提供两种可直接落地的修改方案,任选其一即可:
方案1:表单提交到s1.php完成赋值后跳转s2.php
该方案逻辑分层清晰,后续要扩展s1的表单校验逻辑也更方便:
修改后的s1.php代码
<?php session_start(); // 赋值逻辑移到页面最顶部,避免header跳转前输出内容导致报错 if (isset($_GET['submit'])) { $_SESSION['name'] = $_GET['username']; // 赋值完成后跳转至s2.php展示结果 header('Location: s2.php'); exit(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!-- form的action修改为提交到当前s1.php --> <form action="s1.php" method="get"> <input type="text" name="username"> <input type="submit" name="submit"> </form> </body> </html>
s2.php无需修改,即可正常读取Session值。
方案2:将Session赋值逻辑迁移到s2.php
该方案改动量最小,适合不需要在s1.php做额外表单处理的场景:
修改后的s2.php代码
<?php session_start(); // 直接接收s1.php提交的表单参数,写入Session if (isset($_GET['submit'])) { $_SESSION['name'] = $_GET['username']; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <?php if (isset($_SESSION['name'])) { echo "it set"."<br>"; echo $_SESSION['name']; } else { echo "it not set"; } ?> </body> </html>
该方案下s1.php无需任何修改即可正常运行。
内容的提问来源于stack exchange,提问作者user15141652
相关产品推荐
相关产品推荐

