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; ?>