Leslie
Leslie

Reputation: 107

Trouble using Session variable in header redirect

I am using the following to lock in a location if a user isn't logged in so that I can return to this location once login is successful

$_SESSION['returnURL'] = htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES);

I am having no luck using this session variable in my header redirect. The contents of this variable currently is: /event.php?title=Test&id=16

if($sql->num_rows==1) {
    if (isset($_SESSION['returnURL'])){
        $_SESSION['username'] = $username;
        header("location:$_SESSION['returnURL'])";
        unset($_SESSION['returnURL']);
    } else {
        $_SESSION['username'] = $username;
        header('location:home.php');
    }
} else {
    die(header("location:login.php?login-failed=true&reason=not_found"));
}

When I replace the contents of $_SESSION['returnURL'] with the address that is stored in $_SESSION['returnURL'] it works perfectly. Something is presenting a problem when I use $_SESSION['returnURL'] variable with header I think.

Upvotes: 0

Views: 86

Answers (1)

Progrock
Progrock

Reputation: 7485

Problems with this line:

header("location:$_SESSION['returnURL'])";

Fix the closing bracket:

header("location:$_SESSION['returnURL']");

And use curly braces for array variables in quoted strings:

header("location:{$_SESSION['returnURL']}");

Also:

htmlspecialchars('/event.php?title=Test&id=16', ENT_QUOTES);
// Results in: /event.php?title=Test&id=16

Which is a different URL. You don't need to convert to html entities here.

Upvotes: 1

Related Questions