我正在使用登录系统,我想知道如何将错误发送回表单?
我将在我的项目中亲自使用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...
?>
这只是我刚写的一段代码所以它显然不完整。
谢谢!
答案 0 :(得分: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] = "";
}
}
完成此检查后,只需在HTML中的某处放置$ error_to_display [“password_error”],就像这样echo '<label for="password">Password: ' . $error_to_display[ "password_error" ] . '</label>';
答案 1 :(得分:1)
使用session设置错误..请参阅下面的修改代码..
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;
}
?>