0

我正在开发一个登录系统,我想知道如何将错误发送回表单?
我将亲自在我的项目中使用 AJAX,所以它不会成为真正的问题,但我很想知道纯 php 是如何实现的。

这是表格......在login.php或其他页面上:

<form method="post" action="proccessLogin.php">
    <label for="username">Username: </label>
    <input type="text" name="username" />
    <label for="password">Password: </label>
    <input type="password" name="password" />

    <input type="submit" name="submit" value="Go!" />
</form>

processLogin.php

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];

    if(password is incorrect){
        // send error or add to an error array and then send it.
    }

    etc...
?>

这只是我刚刚写的一段代码,所以它显然不完整。

谢谢!

4

2 回答 2

1

那么你可以去 reload_page 和 $_GET 错误消息路由。

// Set your error messages here
$error_messages = "?password_error=true"
header("Location: http://localhost/url_to_form.php" + $error_messages);
exit();

进入表单文件后,检查已知的错误变量

$error_message_list = array( "password_error" => "Incorrect password" );
foreach ($_GET as $error_name => $error_value) {
    if ( in_array( $error_name, $error_message_list ) ) {
        $error_to_display[$error_name] = $error_message_list[$error_name];
    } else {
        $error_to_display[$error_name] = "";
    }
}

完成此检查后,只需将 $error_to_display[ "password_error" ] 放在 HTML 中的某个位置,如下所示echo '<label for="password">Password: ' . $error_to_display[ "password_error" ] . '</label>';

于 2012-07-09T09:16:05.533 回答
1

使用会话设置错误..参考下面的修改代码..

login.php

<?php
session_start();
?>
<form method="post" action="proccessLogin.php">
    <label for="username">Username: </label>
    <input type="text" name="username" />
    <?php if($_SESSION['u_name_error']) { echo $_SESSION['u_name_error']; unset($_SESSION['u_name_error']); }
    <label for="password">Password: </label>
    <input type="password" name="password" />
    <?php if($_SESSION['pass_error']) { echo $_SESSION['pass_error']; unset($_SESSION['pass_error']); }
    <input type="submit" name="submit" value="Go!" />
</form>

==============
proccessLogin.php
<?php
session_start();

    $username = $_POST['username'];
    $password = $_POST['password'];

    if(password is incorrect){
        // send error or add to an error array and then send it.
    }else{

        //set errors in session..
        $_SESSION['pass_error']= 'error message';
        $_SESSION['u_name_error']= 'error message';
        header("Location: login.php");
        die;
    }

?>
于 2012-07-09T11:27:28.293 回答