PHP表单提交跳转是指在用户通过HTML表单提交数据到PHP服务器后,服务器处理完数据后,将用户重定向到另一个页面或显示一个消息。这种跳转可以通过多种方式实现,例如使用header()函数进行HTTP重定向,或者使用JavaScript进行客户端跳转。
header()函数实现服务器端跳转。<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 处理表单数据
$username = $_POST['username'];
$password = $_POST['password'];
// 假设验证成功
header('Location: success.php');
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>注册页面</title>
</head>
<body>
<form method="post" action="">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">注册</button>
</form>
</body>
</html><?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 处理表单数据
$username = $_POST['username'];
$password = $_POST['password'];
// 假设验证成功
echo '<script>window.location.href = "success.php";</script>';
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>注册页面</title>
</head>
<body>
<form method="post" action="">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">注册</button>
</form>
</body>
</html>header()函数未生效原因:header()函数必须在任何输出(包括空格和换行)之前调用。
解决方法:
header()函数在任何HTML标签或空格之前调用。ob_start()函数开启输出缓冲。<?php
ob_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 处理表单数据
$username = $_POST['username'];
$password = $_POST['password'];
// 假设验证成功
header('Location: success.php');
exit();
}
ob_end_flush();
?>
<!DOCTYPE html>
<html>
<head>
<title>注册页面</title>
</head>
<body>
<form method="post" action="">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">注册</button>
</form>
</body>
</html>原因:用户刷新页面时,浏览器会重新提交表单。
解决方法:
header()函数进行重定向。<?php
session_start();
if (isset($_SESSION['submitted'])) {
header('Location: already_submitted.php');
exit();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 处理表单数据
$username = $_POST['username'];
$password = $_POST['password'];
// 假设验证成功
$_SESSION['submitted'] = true;
header('Location: success.php');
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>注册页面</title>
</head>
<body>
<form method="post" action="">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">注册</button>
</form>
</body>
</html>希望这些信息对你有所帮助!
没有搜到相关的文章