1
I may be missing something, but there’s no way I can see what. I have a simple login code that is behaving (at least it seems to me) in a strange way.
index php.:
session_start();
if(isset($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
<form method="POST" action="process.php">
username
<input type="text" name="username">
password
<input type="password" name="password">
<input type="submit">
</form>
php process.
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($_POST['password'] == 'password' && $_POST['username'] == 'miguel') {
$_SESSION['error'] = 'Loggedin Success';
header('Location: index.php');
}
$_SESSION['error'] = 'Wrong details (username/password)';
header('Location: index.php');
}
$_SESSION['error'] = 'NO POST REQUEST';
header('Location: index.php');
Now, what is happening with this code is that whether I put the wrong or right beliefs (miguel/password) it will always interpret the last block
$_SESSION['error'] = 'NO POST REQUEST';
header('Location: index.php');
How is that possible? Since we have gone through redirects before, the script interpretation (process.php) should not have been interrupted/canceled at this time and redirect us to the destination?
Put elses
containing the blocks the code already does the "supposed":
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($_POST['password'] == 'password' && $_POST['username'] == 'miguel') {
...
}
else {
...
}
}
else {
...
}
But why are they needed in this structure? I’ve always thought that in interpreting a header('Location: ...');
the interpretation of the script itself would be interrupted
The header function only sends the header, you need an Exit after the call. As you are sending several identical headers in sequence, the browser is considering the latter.
– bfavaretto
Haa @bfavaretto. I always thought that redirection occurred at that time. I get it, I know the question sounds stupid, and I’m sorry, but I was getting really messed up about this. You can put a good answer that I accept... I’ve figured out what’s going on then by putting a
die();
after the headers already works so– Miguel
That, die() works too. I won’t let you answer now because I’m on mobile, maybe later.
– bfavaretto
Ok @bfavaretto , rest assured that I will accept yours (if it is good (: ), since you were the first who clarified/solved my doubt
– Miguel
If a good answer appears before, you can accept it if you want :) I did not find the question stupid, this behavior is not obvious at all.
– bfavaretto
@bfavaretto , then my answer :P ?
– Miguel
It took a while, but it came : )
– bfavaretto