$error
始终显示,而不是在脚本中发现错误时显示。我将else
设置为showForm
,这意味着在<?php echo $error; ?>
框中显示$error
上的代码。
谢谢你事先的帮助,我希望很快就能找到这个问题的答案。
<?php
$Password = 'password'; // Password here
if (isset($_POST['submit_pwd'])){
$pass = isset($_POST['pass']) ? $_POST['pass'] : '';
if ($pass != $Password) {
showForm("Wrong password");
exit();
}
} else {
showForm();
exit();
}
function showForm($error="Error, please try again."){
?>
<!DOCTYPE html>
<head>
HEAD CONTENT HERE
</head>
<body>
<section class="container">
<div class="login">
<h1>Login Area</h1>
<br />
<div class="error">
<h2><?php echo $error; ?></h2>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="pwd">
<p><input type="password" name="pass" value="" placeholder="Password"></p>
<p class="submit"><input type="submit" name="submit_pwd" value="Login"></p>
</form>
</div>
</section>
</body>
</html>
<?php
}
?>
您有一个默认的错误值。。因此,当您第一次加载页面时,不会设置$_POST。进入函数的$error值最初应该为空,并且只有在出现错误时才设置。此外,我会将h2标记添加到函数调用中。这样,当没有错误时,空的h2就不会占用任何空间。
<?php
$Password = 'test'; // Password here
if (isset($_POST['submit_pwd'])){
$pass = isset($_POST['pass']) ? $_POST['pass'] : '';
if ($pass != $Password) {
showForm("<h2>Wrong password</h2>");
exit();
}
} else {
showForm();
exit();
}
function showForm($error=""){
?>
<!DOCTYPE html>
<head>
HEAD CONTENT HERE
</head>
<body>
<section class="container">
<div class="login">
<h1>Login Area</h1>
<br />
<div class="error">
<?php echo $error; ?>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="pwd">
<p><input type="password" name="pass" value="" placeholder="Password"></p>
<p class="submit"><input type="submit" name="submit_pwd" value="Login"></p>
</form>
</div>
</section>
</body>
</html>
<?php
}
?>
正如mjayt在回答中所解释的,showForm()
函数将始终输出错误消息。
当没有错误时,不要调用showForm()
函数。
因此,将代码更改为:
if (isset($_POST['submit_pwd'])){
$pass = isset($_POST['pass']) ? $_POST['pass'] : '';
if ($pass != $Password) {
showForm("Wrong password");
exit();
}
}
换句话说,不需要else
条件。或者,你可以把其他代码块留在那里,但什么也不做
exit()
命令不是必需的,因为它是代码执行的最后一件事。无论如何,它会在那之后停止。但是,如果以后添加其他PHP代码,如果不希望处理这些代码,则可能需要exit()。