user6485550 user6485550 - 5 months ago 31
PHP Question

unset of the error message not working in php

Unset of the session for the error message is not working. When I click on

Login
button with empty fields, however, the session works but if I refresh/ reload the page then error message
Undefined index: message in...
appears in this line
unset($_SESSION['message']);

I looked into these questions:

Login error message in php

display error message on same page for login

unset $_SESSION not working

Session unset function not working

& I added the solutions mentioned in those questions but I ended up with error.
What's wrong with the code?

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');
}
}
?>

Answer

Change your php code at home.php like this:

<?php
        if(isset($_SESSION['message']) && $_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.
        }
?>

Because you need to check by isset() that your session variable message is set or not,

Also for more info about isset(), check it out http://php.net/manual/en/function.isset.php