I'm having a problem with what is called I think a Flash Message.
It should clear a key from the $_SESSION array after outputting it, but it clears it before. I know because if I comment the unset() it works (but of course key isn't cleared and persist on refresh) In short this would be the code:
if (isset($_SESSION['error'])) {
echo('<p style="color:red; margin:0">'. $_SESSION['error'] .'</p>');
unset($_SESSION['error']);
}
As it is the echo statement doesn't work. If comment the unset the echo works but the $_SESSION key isn't cleared and i need to clear it after output. Extremely weird, i coded the same in other files and it works flawlessly. Here the whole code for the riddle lovers.
<?php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])){
unset($_SESSION['username']);
if($_POST['password'] =='umsi' && $_POST['username'] == 'chuck') {
$_SESSION['username'] = $_POST['username'];
$_SESSION['success'] = 'Logged in successfuly';
$_SESSION['password'] = $_POST['password'];
header('Location: app.php');
return;
}
else {
$_SESSION['error'] = 'Login incorrect';
header('Location: log.php');
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="main.css">
<title>Log In</title>
</head>
<body>
<div class="log">
<?php
if (isset($_SESSION['error'])) {
echo('<p style="color:red; margin:0">'. $_SESSION['error'] .'</p>');
unset($_SESSION['error']);
}
?>
<h1>Log in</h1>
<form method="post">
<label for="username">Username</label>
<input type="text" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
Thanks to Lawrence Cherone I could realize i missed the return at the end of the else satement.
else {
$_SESSION['error'] = 'Login incorrect';
exit(header('Location: log.php'));
}
now it works!!