我有以下代码:
<html>
<head>
</head>
<body>
<?php
if (!isset($_COOKIE["loggedin"])){
?>
<form action="index.php" method="POST" name="name_form">
Username <input type="text" name="username">
<br/>
Password <input type="text" name="password">
<br/>
Remember Me <input type ="checkbox" name="remember_me" value="1">
<br/>
<input type="submit" name="submit" value="Log in">
</form>
<?php
if(preg_match("/<|>/", $_POST["username"])){
echo "do not log in";
}
else if(preg_match("/<|>/", $_POST["password"])){
echo "do not log in";
}
else {
//Open/create passwords.txt
$passwordsFile = fopen("passwords.txt", "a");
//write users username and password to passwords.txt
$text_written = fwrite($passwordsFile, $_POST["username"] . "," . $_POST["password"] . "\r\n");
fclose($passwordsFile);
setcookie("loggedin", $_POST["username"]);
setcookie("loggedintime", time());
echo "<h1>Welcome " . $_COOKIE["loggedin"] . "</h1>";
echo "You have been logged in for " . $_COOKIE["loggedintime"] . " seconds.";
echo "<nav>
<ul>
<li>Browse books in store</li>
<li>Analytics</li>
<li>Logout</li>
</ul>
</nav>";
}
}
?>
</body>
但它显示了#34;欢迎____,您已登录...&#34;在用户正确完成表单之前的部分,我想知道如果我只想在用户正确填写表单后才能显示该怎么做。
谢谢!
答案 0 :(得分:0)
好吧,按逻辑顺序执行代码。如果用户未登录,则确实如此:
if (!isset($_COOKIE["loggedin"])){
如果没有发布任何表单值,那么这是错误的:
if(preg_match("/<|>/", $_POST["username"])){
这是假的:
else if(preg_match("/<|>/", $_POST["password"])){
因此,执行else
块。完全按照设计。
我怀疑你想检查是否收到任何表格帖子。在这种情况下,您可以将代码包装为:
if (isset($_POST["submit"])){
在评估其余代码之前,会检查submit
按钮是否被按下。
答案 1 :(得分:0)
您似乎正在验证表单并显示欢迎消息而不提交。请检查以下代码。它可能对你有帮助。仅在提交表单后验证表单。
<?php
if (!isset($_COOKIE["loggedin"])) {
?>
<form action="index.php" method="POST" name="name_form">
Username <input type="text" name="username">
<br/>
Password <input type="text" name="password">
<br/>
Remember Me <input type ="checkbox" name="remember_me" value="1">
<br/>
<input type="submit" name="submit" value="Log in">
</form>
<?php
if($_POST) {
if(preg_match("/<|>/", $_POST["username"])){
echo "do not log in";
}
else if(preg_match("/<|>/", $_POST["password"])){
echo "do not log in";
}
else {
//Open/create passwords.txt
$passwordsFile = fopen("passwords.txt", "a");
//write users username and password to passwords.txt
$text_written = fwrite($passwordsFile, $_POST["username"] . "," . $_POST["password"] . "\r\n");
fclose($passwordsFile);
setcookie("loggedin", $_POST["username"]);
setcookie("loggedintime", time());
echo "<h1>Welcome " . $_COOKIE["loggedin"] . "</h1>";
echo "You have been logged in for " . $_COOKIE["loggedintime"] . " seconds.";
echo "<nav>
<ul>
<li>Browse books in store</li>
<li>Analytics</li>
<li>Logout</li>
</ul>
</nav>";
}
}
}
?>