代码正在运行以将用户名与密码匹配,并且如果两者都正确地重定向到另一个页面,但是那和else语句都在运行
代码:
if (isset($_POST['Login'])) {
$IncorrectDetails = 0;
$Username=$_REQUEST['Username'];
$Password=$_REQUEST['Password'];
echo "<p> $Username $Password</p>";
$myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
//reads raw file
$string = fread($myfile,filesize("bin\Account Details.txt"));
//turns the string to array
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('. ', $result);
$AccountDetails[trim($b[0])] = trim($b[1]);
}
//closes file
fclose($myfile);
print_r($AccountDetails);
foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
if ($StoredUsername == $Username){
if ($StoredPassword == $Password) {
header('Location: Main.php');
}
else {
$IncorrectDetails = 1;
}
}
else {
$IncorrectDetails = 1;
}
}
if ($IncorrectDetails == 1){
echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
}
}
如果不正确,它会弹出一个对话框,如果正确,它会重定向
答案 0 :(得分:0)
那是因为重定向不是即时的,PHP代码仍在处理中。
因此,在header('Location: Main.php');
之后执行exit;
,以便在那一点上停止所有脚本,并让重定向工作。
header('Location: Main.php');
exit;
此外,您不要在header()指令之前打印任何内容(删除print_r())。
答案 1 :(得分:0)
if (isset($_POST['Login'])) {
$IncorrectDetails = 0;
$Username=$_REQUEST['Username'];
$Password=$_REQUEST['Password'];
echo "<p> $Username $Password</p>";
$myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
//reads raw file
$string = fread($myfile,filesize("bin\Account Details.txt"));
//turns the string to array
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('. ', $result);
$AccountDetails[trim($b[0])] = trim($b[1]);
}
//closes file
fclose($myfile);
foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
if ($StoredUsername == $Username && $StoredPassword == $Password){
$CorrectDetails = 1;
} else {
$IncorrectDetails = 1;
}
}
if(isset($CorrectDetails) && $CorrectDetails == 1){
header('Location: Main.php');
}else ($IncorrectDetails == 1){
echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
}
}
将您重定向到另一页不是一种正确的方法,而是可以像在else中使用变量一样使用变量,而在循环外部可以重定向到另一页。