0

When I am on homepage.php and I press refresh, I am automatically brought back to login.php despite it not being 30 minutes yet. May I know what went wrong

<?php

session_start();

if (isset( $_SESSION['login_user'] )  && (time() - $_SESSION['login_user'] > 1800)) { // 30 minutes
session_unset();
session_destroy();
} else if (!isset( $_SESSION['login_user'] ) ) { 
    header("Location: login.php");
    exit(); 
}
?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
J. Doe
  • 113
  • 7
  • Your code never sets `$_SESSION['login_user']` – Clive Oct 17 '18 at 12:08
  • 1
    [Your other question](https://stackoverflow.com/q/52827838/1415724) where you used sessions, is using `$_SESSION['login_user']` as the session array, why are you using a new one here; new project? Enable error reporting and you'll get your answer. Btw, in that other question, you did `$_SESSION['login_user'] = '$userid' ;` - that variable in single quotes, will not work, since it's in single quotes. Variables don't get parsed in those; they should just be removed. Another thing; it's completely unsafe; MD5 shouldn't be trusted. – Funk Forty Niner Oct 17 '18 at 12:35
  • Parse your time date_parse(time()) – user-9725874 Oct 17 '18 at 12:36

1 Answers1

2

According to the code snippet you have pasted here, your variable $_SESSION['login_user'] is never set:

<?php

session_start();

if (isset( $_SESSION['login_user'] )  && (time() - $_SESSION['login_user'] > 1800)) { // 30 minutes
session_unset();
session_destroy();
} else if (!isset( $_SESSION['login_user'] ) ) { 
    header("Location: login.php");
    exit(); 
}
?>

You can have it working by assigning a value to it, in this case time(). Try adding this line in your code after verifying $_SESSION['login_user'] is not set:

$_SESSION['login_user'] = time();

That way you can actually check when user has previously logged in and compare it with last 30 minutes as in:

time() - $_SESSION['login_user'] > 1800

You would have something like this:

<?php

session_start();

if (isset( $_SESSION['login_user'] )  && (time() - $_SESSION['login_user'] > 1800)) { // 30 minutes
session_unset();
session_destroy();
} else if (!isset( $_SESSION['login_user'] ) ) {
    $_SESSION['login_user'] = time(); // <-- New line added
    header("Location: login.php");
    exit(); 
}
?>
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Leonardo Leandro
  • 383
  • 1
  • 3
  • 11
  • 1
    Yes - while you're right about the policy it also brushes up against putting too much superfluous language in the answer. To be kind is to provide an answer or comment without talking "down" to the OP. You need not go out of your way to greet them and welcome them here as a good answer, explained well, provides the right message without having to add to it. You did a great job of that with your answer. – Jay Blanchard Oct 18 '18 at 13:26