I’m working on a small, very application-specific CMS. There’s nothing financial going on, and the content isn’t sensitive really (it’s mostly managing relationships between pieces of art), so security isn’t a high priority, but still we’re using a login system with a controlled group of users for each installation.
The entry page has a login form – success sets a session variable to the user table’s PK for the user, and redirects to an arbitrary view page. That variable is also used to track any changes made by that user.
I’m auto_prepending to all pages a small script that just checks if that session variable is set – if not, the user is bounced back to the login page. This works, but seems clumsy – especially since I need to ‘exempt’ the login page, so I used an ugly little hack, which is basically this:
if(!isset($_SESSION['user']) && strpos($_SERVER['PHP_SELF'], '/login.php') !== 0) {
header('Location: /login.php');
}
The above is simplified a little from the actual script, but basically demonstrates what’s happening.
I’m wondering if there’s an established best-practice for something like this – testing for logged-in status and redirecting when that status isn’t set…
tyia
It seems like you’re using the standard approach. But instead of having to include this script in every one of your PHP pages, I would have all requests go through a single index.php file that is responsible for security. That way, you’re certain that there is a single point of failure: your index.php file.
To get this going, you’ll need an .htaccess file if you’re running apache:
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_URI} .*\.php$ RewriteRule ^(.*)$ /index.php?script=$1 </IfModule>Alternatively, you could define a function and include it at the top of every page that requires a logging in:
// in security.php function require_login($redirect_to='/login.php) { if (empty($_SESSION['user'])) { header('Location: ' . $redirect_to); exit(); } } // and in your .php files except for login.php include_once 'security.php'; require_login();You may also want to test that not only ‘user’ is set in the session, but that it includes some identifier (ie. an ID).