0

I'm attempting to make a login system, which then redirects to the appropriate pages if the right details were entered or not.

session_start();

$result = mysqli_query($con, "my query");
if(mysqli_num_rows($result) == 1)
{
    $_SESSION['username'] = $username;
    header("Location: home.php");
}
else
{
    header("Location: login.php");
}

However, if I enter the right details I get: "Undefined variable: _SESSION".

I don't really know what's going wrong here.

3
  • what is your php version? Commented May 1, 2014 at 22:43
  • _SESSION? The name of the session variable is $_SESSION. Was that a spelling mistake? This function returns TRUE if it was successful, so try making a variable receive the return value and the var_dump() it. Commented May 1, 2014 at 22:50
  • No the PHP error definitely misses the $. I have no idea why. Commented May 1, 2014 at 23:00

3 Answers 3

1

You need to make sure that you start session ( session_start()) at the top of every php file where you want to use the $_SESSION superglobal array.

Sign up to request clarification or add additional context in comments.

4 Comments

His code is already showing a session_start() at the very top
@AlanChavez : At the top of this php file, not file where he is redirected(I guess).
Consider also checking if it is started, before that. if(!session_id()) session_start();, otherwise warning may appear, it was something like: Session already started.
Yep, it was a problem with the file it was being directed to, thanks.
1

This sounds like the session_start() call is failing. The most common cause of this is you've started outputting to the browser already. This happens when you have whitespace or HTML before the opening <?php tag, or have any sort of echo/print/printf-type call before your call to session_start().

One way to make sure that the session always gets started first is to use a file that is automatically prepended and have the entire contents of that file be <?php session_start();. To do this, you set the auto_prepend_file INI flag. This does have to be set before any PHP files are loaded, so you either need to use .htaccess or php.ini file.

2 Comments

Yep, it was a problem with the file it was being directed to, thanks.
So the question has been answered @user9993 ? If so, please mark it as solved.
0

Is this a drupal question? If so, this could help you: https://drupal.stackexchange.com/questions/107287/undefined-variable-session-in-template-php

Could you please show the rest of the code prior to session_start()? It's possible/likely that an error (in the previous code) or any output at all before the call to session_start() could be causing your error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.