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

PHP登录表单验证用户名密码后跳转至next.html实现咨询

完整解决方案:HTML登录表单 + PHP验证跳转

第一步:补全你的login.html表单

先把你没写完的HTML表单补全,确保用户名和密码输入框有正确的name属性,这样PHP才能顺利获取用户输入:

<html>
<head>
    <title>Login</title>
</head>
<body>
    <h1><font color="red">Log In To Add Entry!</font></h1>
    <form name="myForm" action="login.php" method="post">
        <fieldset>
            <legend>Login</legend>
            <div>
                <label for="username">Username:</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div>
                <label for="password">Password:</label>
                <input type="password" id="password" name="password" required>
            </div>
            <div>
                <input type="submit" value="Login">
            </div>
        </fieldset>
    </form>
</body>
</html>

第二步:编写login.php验证逻辑

接下来写login.php文件,负责接收表单提交的数据,验证用户名(支持hello/Hello这类大小写匹配)和密码(支持bye/Bye),验证通过就跳转到next.html,失败则提示错误并返回登录页:

<?php
// 先检查是否是POST请求,防止用户直接访问login.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取用户输入,用isset避免未定义索引的警告,trim去掉前后空格
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';

    // 目标用户名和密码
    $targetUsername = 'hello';
    $targetPassword = 'bye';

    // 用strcasecmp做不区分大小写的比较,返回0表示两者相等
    if (strcasecmp($username, $targetUsername) === 0 && strcasecmp($password, $targetPassword) === 0) {
        // 验证通过,跳转到next.html
        header('Location: next.html');
        exit; // 跳转后必须终止脚本执行,避免后续代码运行
    } else {
        // 验证失败,弹出提示并跳回登录页
        echo '<script>alert("Invalid username or password!"); window.location.href = "login.html";</script>';
        exit;
    }
} else {
    // 如果不是POST请求,直接跳回登录页
    header('Location: login.html');
    exit;
}
?>

几个关键注意点

  • 确保login.html、login.php和next.html在同一个目录下,否则要调整跳转的路径。
  • header('Location: ...')执行前不能有任何输出(包括空格、HTML代码),所以PHP代码要放在页面最开头,避免意外输出导致跳转失败。
  • 如果你需要严格区分大小写验证,把strcasecmp换成===直接比较即可:$username === $targetUsername && $password === $targetPassword。
  • 实际项目里别硬编码用户名密码,也建议用加密方式存储密码(比如password_hash),不过这个方案完全符合你当前的简单验证需求。

内容的提问来源于stack exchange,提问作者thtcurlygirl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:00:52