Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : session variable having an undefined offset error

Tags:

php

session

I am a newbie in PHP programming. I am creating a simple login form with sessions. I am passing two session variables : $_SESSION['username'] and $_SESSION['logon']. Here is my code:

    $rowcount = mysqli_num_rows($result);

    if($rowcount == 1){
        session_start();
        $_SESSION['logon'] == "online";
        $_SESSION['username'] = $username;
        header("location:../index.php?username=$_SESSION[username]");

    }

The problem is that when I try to access the $_SESSION['username']variable, it gives me the appropriate value stored in it, but when I try to access the $_SESSION['logon'] variable, it gives me an undefined offset error.

like image 620
Herry Potei Avatar asked Jul 04 '26 08:07

Herry Potei


1 Answers

2 things:-

1.session_start(); need to be top on the each page(best to add in separate file and then include that file to every other file)

2.

$_SESSION['logon'] == "online"; //it's comparison not assignment

need to be:-

$_SESSION['logon'] = "online"; // now it's an assignment

Note:- you can get Warning: Cannot modify header information - headers ... multiple times, when you use session_start() in middle of the page.

Reference:-

1.Why setcookie( ) and session_start( ) Want to Be at the Top of the Page

2.Where exactly do I put a SESSION_START?

3.When do I have to declare session_start();?

like image 78
Anant Kumar Singh Avatar answered Jul 05 '26 20:07

Anant Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!