如果未设置会话,则PHP标头重定向不起作用

如果未设置会话,则PHP标头重定向不起作用

问题描述:

I'm trying to check if the user hasnt logged in on a cart.php, if they arent -redirect them to login.php.

This isn't working so I tried putting it in an elseif statement. If they are logged in and are on the cart page, redirect them to the cart page, and if they arent redirect them to the login page.

It is working in the sense that it redirects, yet if I login, it still redirects to login.php.

Also I'm not sure why none of the JS alerts are working.

if (isset($_SESSION['username'])){
    header("Location: http://localhost/techiteasy/cart.php");
}
else if (!isset($_SESSION['username'])){
    header("Location: http://localhost/techiteasy/login.php");
    echo '<script language="javascript">';
    echo 'alert("Please Login/Register")';
    echo '</script>';
}

After a redirect you can't add more code, the new page will call and the script of the new one will run.

You need somthing transfer from a page to another.

Usually i use a cookie with a short time (2-5 seconds), the new page will call check if the cookie is set, if it is show the alert and unset the cookie.

Here in the code you can see i put only an if statement (without else or else if) cause when the script fire the header location the next one code won't run and the new page will load.

if (!isset($_SESSION['username'])){
    setcookie('notlogged', true, time() + 3;)

    header("Location: http://localhost/techiteasy/login.php");     
}
header("Location: http://localhost/techiteasy/cart.php");

In the login.php

if (isset($_COOKIE['notlogged']) && $_COOKIE['notlogged'] == true){
    echo '<script language="javascript">';
    echo 'alert("Please Login/Register")';
    echo '</script>';

    unset($_COOKIE['notlogged']);
}

Try this ;)

You can also not set an expired time, it is just to avoid errors, but remind to unset every time, in other case the user only logs without passing from cart will wiew the alert.

Try this on PHP5

    if(isset($_SESSION['username'])){ header("Location: http://localhost/techiteasy/cart.php"); 
    }
    else{
    if(!isset($_SESSION['username'])){
     echo '<script>alert("Login with vaild user and pass");</script>';
header("Location: http://localhost/techiteasy/login.php");
    exit;
     }}

For PHP7

    if(isset($_SESSION['username'])){ header("Location: http://localhost/techiteasy/cart.php, true, 301"); 
    }
    else{
    if(!isset($_SESSION['username'])){ 
     echo '<script>alert("Login with vaild user and pass");</script>';
header("Location: http://localhost/techiteasy/login.php, true, 301");
    exit;
     }}

You can simply use as like below. Do not need to check negative condition again. Simply use if-else.

if (isset($_SESSION['username'])){
    header("Location: http://localhost/techiteasy/cart.php");
}
else{
    header("Location: http://localhost/techiteasy/login.php");
    echo '<script language="javascript">';
    echo 'alert("Please Login/Register")';
    echo '</script>';
}