0

I have a script called login.php which takes user information supplied via a form and checks whether the entered login information is valid. If the information is not valid, the following code is called:

$GLOBALS['user_login_fail'] = true;
header('Location: ../index.php'); //this displays index.html

In index.html, there is an error message that is shown if the user entered invalid login information:

<?php 

if($GLOBALS['user_login_fail'] == true)
{
    echo '<div> Login credentials could not be verified </div>';
}
else
{
    echo "no error";
}
?>

However, after being redirected I get an error: Notice: Undefined index: user_login_fail. What's wrong here?

user3361761
  • 259
  • 1
  • 4
  • 13

2 Answers2

2

I think you're getting global variables and session variables confused.

Globals exist everywhere in the current scope, but a browser redirect creates a new scope. Session variables persist across browser redirects.

Try this:

session_start();
$_SESSION['user_login_fail'] = true;

and

session_start();

if(isset($_SESSION['user_login_fail']) && $_SESSION['user_login_fail']) {
    echo '<div> Login credentials could not be verified </div>';
} else {
    echo "no error";
}
scrowler
  • 23,403
  • 9
  • 52
  • 87
2

It seems (as stated already) that you are confusing $_GLOBALS with $_SESSION in php. I'll tell you straight away: $_GLOBALS are bad practice in php.


Why globals are bad

When people talk about global variables in other languages it means something different to what it does in PHP. That's because variables aren't really global in PHP. The scope of a typical PHP program is one HTTP request. Session variables actually have a wider scope the PHP "global" variables because they typically encompass many HTTP requests.


Basically you want to be using $_SESSIONS. That would be done like this:

As the validation part:

session_start();
$_SESSION['user_login_fail'] = true;
header("Location: index.php");

And as your index.php

session_start();

if(isset($_SESSION['user_login_fail']) && $_SESSION['user_login_fail'] == TRUE) {
    echo '<div> Login credentials could not be verified </div>';
} else {
    echo "no error";
}
Community
  • 1
  • 1
Darren
  • 12,786
  • 3
  • 34
  • 71