表单提交是Web开发中最基本的交互方式之一,通常涉及HTML前端表单和PHP后端处理。
<form action="process.php" method="post">
<input type="text" name="username">
<input type="submit" value="提交">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
// 处理数据...
header("Location: success.php");
exit;
}
?>
错误表现:Warning: Cannot modify header information - headers already sent by...
原因:
header()
函数之前解决方案:
header()
调用前没有任何输出(包括空格和空行)<?php
标签前没有空白字符错误表现:页面不断重定向到自身
原因:
解决方案:
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST['username'])) {
// 处理数据...
header("Location: success.php");
exit;
}
错误表现:重定向到错误URL或404页面
原因:
解决方案:
// 使用绝对URL路径
header("Location: http://example.com/success.php");
// 或者使用基于根目录的相对路径
header("Location: /success.php");
错误表现:重定向后脚本继续执行
原因:
header()
后未调用exit
或die
终止脚本执行解决方案:
header("Location: success.php");
exit; // 必须添加
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 验证数据
if (empty($_POST['username'])) {
header("Location: form.php?error=1");
exit;
}
// 处理数据
$username = htmlspecialchars($_POST['username']);
// 重定向
header("Location: success.php");
exit;
}
?>
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_SESSION['form_data'] = $_POST;
header("Location: process.php");
exit;
}
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_SESSION['token'] !== $_POST['token']) {
header("Location: form.php?error=token");
exit;
}
// 处理数据...
header("Location: success.php");
exit;
}
通过以上方法和最佳实践,可以有效地解决HTML和PHP表单提交中的重定向错误问题。