Building Browsergames: forcing users to log in (PHP)

While we’ve been building our game, we haven’t really been focusing too much on securing our game against users who haven’t logged in yet. Most of our pages rely on the fact that the user needs to be logged in to see them, and they’ll break horribly if the user isn’t. So today, we’re going to add some handling to our game that will make sure that users are logged in before they try to access something.

You might be wondering how we’re going to figure out whether a user is logged in or not. And the answer to that question is a lot simpler than you might think: we’ll just use what we already have.

Any of our pages that use our stats code have a snippet at the top of them that retrieves the current user’s User ID, so that we can interact with their stats. We can use that code as our starting point – here’s a refresher on what it looks like:

 

session_start();
 
require_once 'config.php';		// our database settings
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
	or die('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT id FROM users WHERE UPPER(username) = UPPER('%s')",
			mysql_real_escape_string($_SESSION['username']));
$result = mysql_query($query);
list($userID) = mysql_fetch_row($result);

All we do in that code is retrieve the username we stored into session, and then use that value in our SQL to find out what the user’s User ID is. We can easily modify that code, to do a quick check to see what was returned and redirect based on whether or not anything came back:

 

<?php
 
session_start();
 
require_once 'config.php';		// our database settings
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
	or die('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT id FROM users WHERE UPPER(username) = UPPER('%s')",
			mysql_real_escape_string($_SESSION['username']));
$result = mysql_query($query);
list($userID) = mysql_fetch_row($result);
if(!$userID) {
	// not logged in!
	header('Location: login.php');	
}
 
?>

If you save that file as login-check.php, you can now add this line to any file that you want to require a login for:

require_once 'login-check.php';

And if a user attempts to access the page without having logged in first, they’ll be automatically redirected to the login page. Easy!