You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现表单提交至邮件脚本后传递数据预填后续表单

解决方案:使用PHP会话(Session)传递表单数据

要实现非URL传参的方式将form1的数据预填到form2中,**PHP会话(Session)**是最简洁安全的方案——它在服务器端存储数据,不会暴露在URL或页面源码中(除了预填的表单值),且能跨页面稳定保持数据。

步骤1:修改formMailer.php,存储数据到Session

在跳转前开启Session,将form1提交的用户名和邮箱存入Session:

<?php
// 开启会话,必须在任何输出之前调用
session_start();

// 接收并处理form1的POST数据(建议添加基础验证)
$name = isset($_POST['userName']) ? trim($_POST['userName']) : '';
$email = isset($_POST['userEmail']) ? trim($_POST['userEmail']) : '';

// 将数据存入Session
$_SESSION['userName'] = $name;
$_SESSION['userEmail'] = $email;

// 原邮件发送代码保持不变
$message = "\r\nYour Name: " . $name . "\r\nYour Email: " . $email;
$subject = "Subject of email";
$mailto = "recieving@email.com";
$separator = md5(uniqid(time()));
$eol = "\r\n";

$headers = "From: " . $name . " <" . $email . ">" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed;" . $eol . " boundary=\"" . $separator . "\"" . $eol;
$headers .= "This is a MIME encoded message." . $eol . $eol;

$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
$body .= $message . $eol;

mail($mailto, $subject, $body, $headers);

// 跳转至form2页面,跳转后终止脚本执行
header('location: /formFolder/form2.php');
exit;
?>

步骤2:修改form2.php,读取Session数据预填表单

在form2页面开启Session,读取Session中的数据并填充到输入框的value属性中,同时用htmlspecialchars转义内容防止XSS攻击:

<?php session_start(); ?>
<form id="form2" action="nextAction" method="post">
   Name:&nbsp;<input type="text" id="userName" name="userName" value="<?php echo htmlspecialchars($_SESSION['userName'] ?? '', ENT_QUOTES); ?>">
   Email:&nbsp;<input type="email" id="userEmail" name="userEmail" value="<?php echo htmlspecialchars($_SESSION['userEmail'] ?? '', ENT_QUOTES); ?>">
   Other Data:&nbsp;<input type="text" id="other_userData" name="other_userData" value="">
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</form>

<?php
// 可选:form2提交后若不再需要这些数据,可手动销毁Session变量
// unset($_SESSION['userName']);
// unset($_SESSION['userEmail']);
?>

关键注意事项

  • Session开启时机:session_start()必须在页面任何输出(包括HTML标签、空格、换行)之前调用,否则会触发报错。
  • 数据验证:建议在接收POST数据时添加格式验证(比如检查邮箱合法性、用户名非空),避免无效数据流入Session。
  • XSS防护:必须用htmlspecialchars()转义输出到HTML中的变量,防止恶意脚本注入。
  • Session生命周期:Session默认会在用户关闭浏览器后失效,也可手动销毁不再需要的变量,减少服务器资源占用。

内容的提问来源于stack exchange,提问作者Vera de Milo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 21:09:50