【发布时间】:2016-10-22 12:50:55
【问题描述】:
未设置错误消息的会话不起作用。但是,当我单击带有空字段的Login 按钮时,会话可以工作,但是如果我刷新/重新加载页面,则错误消息Undefined index: message in... 出现在这一行unset($_SESSION['message']);
我调查了这些问题:
Login error message in php
display error message on same page for login
unset $_SESSION not working
Session unset function not working
& 我添加了这些问题中提到的解决方案,但最终出现错误。 代码有什么问题?
home.php
<?php
ob_start();
session_start();
require 'connect.php'; //successful connection to db
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function login(file, div){
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState==4 && xhttp.status == 200){
document.getElementById(div).innerHTML = xhttp.responseText;
}
}
xhttp.open('GET',file,true);
xhttp.send();
}
</script>
</head>
<body>
<form action="loginform.php" method="GET">
Username:<input type="text" name="uname"></br>
Password:<input type="password" name="pass"></br><br>
<input type="submit" value="Login" onclick="login('loginform.php','errormsg');"><br>
<div id="errormsg">
<?php
if($_SESSION['message']){
echo $_SESSION['message'];
unset($_SESSION['message']);//works for blank or wrong inputs but if page is refreshed error: 'Undefined index: message in...' appears in this line.
}
?>
</div>
</form>
</body>
</html>
loginform.php
<?php
ob_start();
session_start();
require 'connect.php';
if(isset($_GET['uname']) && isset($_GET['pass'])){
$uname = $_GET['uname'];
$pass = $_GET['pass'];
if(!empty($uname) && !empty($pass)){
$query = "SELECT `Username` FROM `userinfo` WHERE `Username`='$uname' AND `Password`='$pass'";
$query_run=mysqli_query($dbconnect,$query);
$num_row = mysqli_num_rows($query_run);
if($num_row == 1){
header('Location:welcome.php');
}else{
$_SESSION['message'] = 'Wrong Username or Password missing.';
header('Location:home.php');
}
}else{
$_SESSION['message'] = 'Enter values';
header('Location:home.php');
}
}
?>
【问题讨论】: