user9993
user9993

Reputation: 6170

PHP - Undefined Session

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.

Upvotes: 0

Views: 57

Answers (3)

Felipe
Felipe

Reputation: 11887

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.

Upvotes: 0

potashin
potashin

Reputation: 44581

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.

Upvotes: 1

user3477804
user3477804

Reputation:

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.

Upvotes: 1

Related Questions