Reputation: 1023
Here is my code
<?php
if (!isset($_SESSION)) { session_start(); }
if (!isset($_SESSION['username'])) { header("Location: index.php"); }
ob_start();
if($_POST) {
$id = $_POST['book_id'];
$command = $_POST['command'];
$sourcePage = $_POST['source'];
} else if ($_GET){
$command = $_GET['command'];
$sourcePage = $_GET['source'];
$id = $_GET['book_id'];
} else {
header("Location: index.php");
}
// if command is 2 then show cart content
if($command == 2) {
showCart();
// if command is 1 then add book to cart
} else if($command == 1) {
addToCart($id);
header("Location: $sourcePage");
// if command is 0, then remove book from cart
} else if($command == 0) {
deleteFromCart($id);
header("Location: $sourcePage");
} else if(!isset($command)){
header("Location: index.php");
}
ob_flush();
?>
Why is it that even if I'm not logged in, I'm not redirected?
Upvotes: 0
Views: 198
Reputation: 8297
From my experience, every time there is redirect via headers, its following connected code tends to execute.
For example : if you have an else/else if
along with an if
(which has the redirect code) then they will also be executed and the redirect never happens. However if you break up the conditions into individual ifs
then after entering one if
if a redirect is present such that there is no succeeding code after that header code in the if
then the redirect will happen.
Better to use die()
/exit()
all over to avoid discrepancies.
Upvotes: 0
Reputation: 144
Using exit() or die functions may fix the problem. But there is only very very limited amount of situations where actually need to use one of these functions.
I think you can enhance if else conditions by putting some more conditions. But this will increase your lines of code.
Upvotes: 1
Reputation: 60
is it possible that the page is simply refreshing under the condition that $_POST
or $_GET
exists, falling into one of the later header("Location: ...")
commands?
If so, you'd want to fix the problem by adding a die();
if (!isset($_SESSION['username'])) { header("Location: index.php"); die(); }
Upvotes: 1