Monday, May 14, 2012

Handling User Login

The Coursework requires the logging in of users. A simple HTML + CSS login form was created, and linked to the main database. The form sends the user to a file called "processLogin.php".

Note: The file references another script: "mysqlHander.php". It can be found at the end of this post.

Getting and Cleaning User Input

First, the user input is sanitised, and the password is hashed. The original POST variable is emptied, for security.

$u = mysql_real_escape_string($_POST['username']);
$p = hashPassword($_POST['password']);
$_POST['password'] = "";

The SQL query is built and executed. The results are stored in a variable called $result. The results are then checked:

$sql = "select username from user where username = '" . $u . "' and password = '" . $p . "'";
$result = executeQuery($sql);

if ($result) {
 while ($row = mysql_fetch_array($result)) {
  if ($row['username'] == $u) {
   $logged_in = true;

If the query is successful (i.e. the username and password match), the user is logged in.

A cookie is saved on the user's computer, which lasts for a week:

if ($logged_in) {
 setcookie("user", $_POST['username'], time() + (604800));
} else {
 header('Location:login.php?bad_login=1&username=' . $_POST["username"]);

The logged in user is automatically redirected back to the homepage. The homepage will display options relating to the coursework. Not all functionality exists at this stage.

Notice the common navigation bar at the top of the page. That is achieved using PHP include commands.

If something went wrong, they are redirected back to the login page. The login page is pre-filled with the username, and they are informed that their login was not correct.


Handling user login using PHP and MySQL is a fairly straightforward task, but one must know the steps involved (including the necessary escaping and hashing).

Download Source Code

You can download the complete source code used in this post below.

No comments:

Post a Comment