0

I am trying to create a snippet of PHP that checks if the user has signed up using Sessions when they reach my index page, and if they haven't, I will redirect them to the signup page.

I have started the Session after the user has signed up, but I can't seem to check on my index page to check if the session has started or not.

Sign up PHP:

    session_start();

    //create connection

    //check for errors in the form

    if(!$error) {

        //insert values from form to sql database

        $_SESSION['login_user'] = $username;

        //email user


    }
?>

index.php

<?PHP

    include("signupphp.php");

    if(!$username) {

        echo '<script>location.href = "https://google.com";</script>';

    }

 ?>

Ideally, I would want when the user signs up, it creates the session, and whenever they go to the index.php, it checks to see whether they have signed up, and if they haven't, it will redirect them to the signup page.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
CoderColin14
  • 51
  • 1
  • 8

2 Answers2

1

If I'm understanding you correctly you want to check if the session has been set with the username, correct?

In that case you're checking the wrong variable.

if( !isset($_SESSION["login_user"]) ){
    header("Location: https://google.com");
    exit();
}

This should do the trick. I also changed your redirect to a PHP redirect.

Linus Juhlin
  • 1,175
  • 10
  • 31
0

The sessions will propagate between the pages of your site. So, in sign up:

$username = $_POST['username']//The username could be obtained from a login form
sesion_start();
$_SESSION['login_user'] = $username;
$_SESSION['valid'] = true;

will keep $username available for index.php

session_start()
if( ! $_SESSION['valid']){
    echo '<script>location.href = "https://google.com";</script>';
}
Byron Rodríguez
  • 191
  • 2
  • 10