Site Builder
Editing:
auth.php
writable 0666
<?php /***************************************************************** * Authentication + graceful error helpers *****************************************************************/ session_start(); require_once __DIR__.'/db.php'; // provides $db (PDO) /* -------------------------------------------------------------- 0. Global error handler –– optional but handy ----------------------------------------------------------------*/ set_exception_handler(function($ex){ error_log($ex); // write to server log http_response_code(500); echo '<!doctype html><title>Error</title> <h1>Something went wrong</h1> <p>Please try again or contact support.</p>'; exit; }); /* -------------------------------------------------------------- 1. Friendly pages ----------------------------------------------------------------*/ function session_expired(): void { http_response_code(440); // 440 Login Time‑out (MS IE extension) header('Location: /members/login.php'); exit; } function forbidden_page(): void { http_response_code(403); echo '<!doctype html><title>Access denied</title> <h1>Access denied</h1> <p>You do not have permission to view this page.</p> <p><a href="/members/dashboard.php">Back to dashboard</a></p>'; exit; } /* -------------------------------------------------------------- 2. Login requirement helper • call require_login() → only checks session • call require_login($slug) → also ACL check against user_pages ----------------------------------------------------------------*/ function require_login(string $slug = ''): void { if (empty($_SESSION['uid'])) { session_expired(); // 440 Session expired } /* fetch once, cache */ $user = current_user(); /* 1. super‑user shortcut ----------------------------------- */ if (($user['role'] ?? 'user') === 'admin') { return; // admin may access everything } /* 2. normal ACL check -------------------------------------- */ if ($slug !== '') { static $stmt = null; global $db; $stmt ??= $db->prepare(" SELECT 1 FROM user_pages up JOIN pages p ON p.id = up.page_id WHERE up.user_id = ? AND p.slug = ? LIMIT 1 "); $stmt->execute([$user['id'], $slug]); if (!$stmt->fetchColumn()) { forbidden_page(); // 403 Access denied } } } /* -------------------------------------------------------------- 3. Cached accessor for the current user row ----------------------------------------------------------------*/ function current_user(): array { static $row = null; if ($row !== null) return $row; global $db; $s = $db->prepare('SELECT * FROM users WHERE id = ?'); $s->execute([$_SESSION['uid']]); return $row = $s->fetch(PDO::FETCH_ASSOC) ?: []; }
Save changes
Create folder
writable 0777
Create
Cancel