Change session expiry for logged in users

with session_start(); a cookie is automatically generated with the session ID, when a user logs in I want this cookie to have an expiry date with a long length to stop users needing to keep logging in whenever they start a new session.
init.php is required on each page using <?php require "init.php"?> therefore not needing to add session_start(); on each page.

Login:

<?php

require "init.php";

postonly($_SERVER);

$user = trim($_POST["user"]);
$pass = $_POST["pass"];

if (!$user || !$pass)
	postfail("Please fill out all fields");

if (strlen($user) > 20 || strlen($pass) > 128)
	postfail("Bad request");

$q = $db->prepare("SELECT rowid, * FROM users WHERE username = ?");
$q->bindValue(1, $user);
$r = $q->execute();
$r = $r->fetchArray(SQLITE3_ASSOC);
if (!$r)
	postfail("Invalid username");

if (!password_verify($pass, $r["password"]))
	postfail("Invalid password");

$q = $db->prepare("UPDATE users SET session = ? WHERE rowid = ?");
$q->bindValue(1, session_id());
$q->bindValue(2, $r["rowid"]);
$q->execute();
$_SESSION["uid"] = $r["rowid"];


echo("Successfully logged in! Redirecting you shortly.");

?>

Init.php

<?php

require "lib.php";

session_start([
	"use_strict_mode" => true,
]);

try {
	if (file_exists("data"))
		$db = new SQlite3("data/db", SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
	else if (file_exists("../data"))
		$db = new SQlite3("../data/db", SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
} catch (Exception $e) {
	error("Failed to open database");
}

if (!$db)
	error("Failed to open database");

if (array_key_exists("uid", $_SESSION)) {
	$q = $db->prepare("SELECT session FROM users WHERE rowid = ?");
	$q->bindValue(1, $_SESSION["uid"]);
	$r = $q->execute();
	$r = $r->fetchArray(SQLITE3_ASSOC);


	$good = true;

	if (user()["class"] == 0) {
		session_destroy();
		$q = $db->prepare("UPDATE users SET session = '' WHERE rowid = ?");
		$q->bindValue(1, $_SESSION["uid"]);
		die("<!DOCTYPE html>\n<p>You have been banned. Please reload.</p>");
	}
}
else
	$good = false;

?>

Since there’s nothing that matters in the session data for a non-logged in user, there’s no good reason to want to manage two different session lifetimes.

To implement a ‘remember me’ login feature, you would typically generate a unique token, similar to a session id, store this in a cookie and in a row in a database table, along with the user id that it corresponds to, then upon each page request, if the token is present, query to get the corresponding user id, if any, and set your normal user id session variable that indicates who is logged in, that gets used throughout the rest of the code.

1 Like

What’s my best best at approaching this, where should I implement something like in what file?
I’m kind of new to creating new PHP, but I’m okay with implementing it into my site as it’s my friends code from another site we made. Hense my cry for help lol

Sponsor our Newsletter | Privacy Policy | Terms of Service