Skip to content

Instantly share code, notes, and snippets.

@timhberry
Created January 8, 2023 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timhberry/907a666c1cce50dd8360d9cc10a7ef6c to your computer and use it in GitHub Desktop.
Save timhberry/907a666c1cce50dd8360d9cc10a7ef6c to your computer and use it in GitHub Desktop.
<?php
// called by every page that should only be showed to a logged in user
// will ensure a valud session exists either in the local session cache
// or via a session key stored in a cookie which can be retrieved
// from the sessions table in the database
// first check for existing session ID
session_start();
if ((isset($_SESSION['id']) && $_SESSION['id'] != session_id()) || !isset($_SESSION['loggedin']) || !$_SESSION['loggedin']) {
// no valid session ID has been found; check cookie next
if (isset($_COOKIE['session_key'])) {
$session_key = $_COOKIE['session_key'];
// retrieve cookie details from sessions table
// connect to database
$db_params = parse_ini_file( dirname(__FILE__).'/dbparams.ini', false );
$conn = mysqli_connect($db_params['host'], $db_params['user'], $db_params['password'], $db_params['dbname']);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// check database for a matching session key
$stmt = $conn->prepare("SELECT account_id, login_time FROM sessions WHERE session_id = ?");
$stmt->bind_param('s', $session_key);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// we have found a matching session key, retrieve variables
$stmt->bind_result($userid, $login_time);
$stmt->fetch();
// check the login time
if (strtotime($login_time) < strtotime('-7 day')) {
// previous login time is over 7 days ago, so we must invalidate this session
// forwarding to the logout page will do all of this for us
header("Location: logout.php");
}
// now update the login time in the database
$update = $conn->prepare("UPDATE sessions SET login_time = now() WHERE session_id = ?");
$update->bind_param('s', $session_key);
$update->execute();
// and update the local session
$_SESSION['id'] = session_id();
$_SESSION['userid'] = $userid;
$_SESSION['loggedin'] = true;
// at this point we are okay to move on with whichever script called us!
} else {
// session key was not found in the database, so user must log in
session_destroy();
header("Location: login.php");
exit();
}
} else {
// no cookie was found either, so user must log in
session_destroy();
header("Location: login.php");
exit();
}
}
// if the original if statement does not evaulate to true, we are already logged in
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment