Jump to: navigation, search

PHP Session to end user session in a specific time

From w3cyberlearnings

Login Page (login.php)

  • This page use for login.
  • If user login name:bob, and login password: pbob
  • Direct user to the home page.
  • If incorrect login name and password, will display message to user.
  • Set session to be expired within 30 minutes
<?php
session_start();
if (isset($_POST['LOGIN'])) {
	$lgName = $_POST['lg_name'];
	$lgPass = $_POST['lg_password'];
	if ($lgName == 'bob' && $lgPass == 'pbob') {
		$_SESSION['user'] = $lgName;
		//start logged in time
		$_SESSION['start'] = time();
		// ending a session in 30     minutes from the starting time
		$_SESSION['expire'] = $_SESSION['start'] +  (30 * 60);
		header('Location: home.php');
	} else {
		echo "Please enter the correct Username or Passwod!";
	}
}
?>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>LOGIN</title>
</head>
<body>
	<form name="frm_login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
		<table>
		  <tr>
                     <td>Username </td>
                     <td><input type="text" name="lg_name"></td>
                  </tr>
		  <tr>
                      <td>Password</td>
                      <td><input type="password" name="lg_password"></td>
                  </tr>
		  <tr>
                     <td colspan="2"><input type="submit" value="SignIn" name="LOGIN"></td>
                  </tr>
		</table>
	</form>
</body>
</html>

user home page (home.php)

  • In home page will check the user session against the session expired (Session expired set to:30 min)
  • If the session expired redirect to the logout.php page.
  • You may not need to use: <meta http-equiv="refresh" content="1">,

the reason I add this script in order to see the page refresh and to display the count.

<html>
	<head>
		<meta http-equiv="refresh" content="1">
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title></title>
	</head>
	<body>
		<?php
		session_start();
		$name = "";
		if (!isset($_SESSION['user'])) {
			echo "Please Login again";
			echo "<a href='login.php'>Click Here to Login</a>";
		} else {
			$now = time(); // checking the time now when home page starts
			$name = $_SESSION['user'];
			if ($now > $_SESSION['expire']) {
				header("Location:logout.php");
			}
		}
		?>
		<?php
		echo 'Now: ' . $now . ' --till:' . $_SESSION['expire'] . '<br/>';
		echo 'Your name: ' . $name;
		?>
	</body>
</html>

logout page (logout.php)

  • This page will destroy all the session and redirect user back to login.php page.
<?php
session_start();
session_destroy();
header("Location:login.php");
?>

Navigation
Web
SQL
MISC
References