1

I have some code for a login form. It receives info from a form. A username and a password. In my logic i store the username and password to dollar variables within a function that checks the data was received, remember me box was ticked and password/username combination is correct.

My question is - how can I refer to the $username in another page? I start session on each page but the username doesn't seem to make it. Code is as below.

if (isset($_POST['username'])){

    $username = $_POST['username'];
    $password = $_POST['password']; 
    $rememberme = $_POST['rememberme']; 


    $sql = "SELECT  * from user_table WHERE username='".$username."' AND password='".$password."'LIMIT 1";
    $res = mysqli_query($sql_con,$sql);
    if (mysqli_num_rows($res) == 1) {

        if ($rememberme=="on"){
           setcookie("username",$username, time() +7200);
        } else if($rememberme==""){
            $_SESSION['username']=$username;
        } 
        header("location: postjoke.php");
        // use this for storing logged in name echo $_SESSION['username'];
        //$_SESSION['username']) || isset($_COOKIE['username']
        echo '<h1><a style=color:black; href = "postjoke.php">Cick here to post a joke</a></h1>';

        exit(); 
    } else {
        echo "invalid login";
        echo '<li><a href = "index.php">Home</a></li>';
        exit();
    }
}

There is definitely a simple solution for this, many thanks in advance guys.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149

1 Answers1

0

It seems that you forgot put

session_start()

at the beggining of your code

  • Well [Who would have guessed that](http://stackoverflow.com/questions/36666805/how-to-store-a-php-variable-within-a-function-for-use-on-another-page#comment60926160_36666805) I hope you dont intend to continue your SO career vampiring others comments into your answers. People can get a little touchy about that – RiggsFolly Apr 16 '16 at 17:58
  • Hi sorry, that is just a part of the code. I have session_start() at the beginning of the code. – Adam McMurchie Apr 16 '16 at 19:32