PHP表单重定向时如何保留数据?表单数据传递异常求助
你遇到的问题核心是:header("location: page2.php") 会发起一个全新的GET请求,原来表单提交的POST数据不会被自动携带到page2.php,所以那边拿不到$_POST["surname"]。以下是几种可行的解决方案:
方案1:使用SESSION存储数据(推荐用于敏感信息)
SESSION是服务器端的存储机制,适合传递需要保密的数据。
修改原页面代码:
<?php session_start(); // 必须在输出任何内容前开启session if( isset($_POST['btn']) ) { $surname = $_POST["surname"]; $_SESSION['surname'] = $surname; // 把数据存入session header("location: page2.php"); exit; // 重定向后一定要exit,避免后续代码执行 } ?> <form id="frm" name="frm" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" > <input name="surname" type="text"> <button class="btn" type="submit" name="btn">continue</button> </form>
page2.php代码:
<?php session_start(); if(isset($_SESSION['surname'])){ echo $_SESSION['surname']; // 用完后可以销毁该session变量,避免残留 unset($_SESSION['surname']); } ?>
方案2:直接将表单提交到page2.php(最简单的方式)
如果不需要在原页面做额外处理,直接把表单的action指向page2.php,跳过当前页面的中转:
<form id="frm" name="frm" action="page2.php" method="post" > <input name="surname" type="text"> <button class="btn" type="submit" name="btn">continue</button> </form>
此时page2.php直接通过$_POST["surname"]就能获取数据:
<?php if(isset($_POST['btn'])){ echo $_POST["surname"]; } ?>
方案3:通过GET参数传递(仅适合非敏感数据)
把数据拼接到重定向的URL中,用GET方式传递,但注意这种方式数据会暴露在地址栏,不适合密码、手机号等敏感信息:
修改原页面的重定向代码:
<?php if( isset($_POST['btn']) ) { $surname = $_POST["surname"]; // 用urlencode处理特殊字符,避免URL解析错误 $encoded_surname = urlencode($surname); header("location: page2.php?surname=$encoded_surname"); exit; } ?>
page2.php代码:
<?php if(isset($_GET['surname'])){ // 用urldecode解码,还原原始内容 echo urldecode($_GET['surname']); } ?>
内容的提问来源于stack exchange,提问作者marco
相关产品推荐
相关产品推荐

