Monday, May 7, 2012

Coursework 2 - Part 1

The second part of the Course work was to add a sense of users and sessions to the game. This was done by adding a login screen to the game. The user session goes on till the end of the game, or till the user logs out. Another feature of the game which was added at this stage is the high score system. The hall of fame is shown on the game screen on the right of the game. Also, after the game is over, the game is redirected to the hall of fame page. Here a user can play again or log out to stop playing, redirecting to the login screen again.

Creating the Database

The first thing which was done was creating a database to hold the data which we need for this application. This application does not require any complex databases. As a matter of fact, I am just using a single table. The database was created using MySQL Server Community Edition. I prefer to use MySQL Workbench to manage the database. This tool has an SQL Window in which one can write SQL commands and execute them in the database. I created a database in MySQL called cannon_game and then create a table called login. The following is the SQL command used to create this table:

CREATE TABLE `login` (
  `user_id` int(3) NOT NULL AUTO_INCREMENT,
  `username` varchar(10) NOT NULL,
  `password` varchar(10) NOT NULL,
  `highscore` double DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1$$

A couple of rows were created to have some sample data. These were created with the following SQL Command:

INSERT INTO `cannon_game`.`login` (`user_id`,`username`,`password`,`highscore`)
VALUES
('user_id','username','password','highscore');

The test data can be seen with the following command:

SELECT * FROM 'cannon_game'.'login';

The picture below shows the sample data:

Figure 1: The sample data

With this database in place, I was able to start to work on the login screen of the game.

The Login Screen

The next step was to create the login screen. A php file with the name of login.php was created for the login screen. This login screen is made up of a form with a username and password. The password is a password input box in HTML so that the password will be masked. There is a checkbox for creating a new user. Also, it has a submit button so that the form will make a POST request to the server page.  The picture below shows the login screen after being formatted with CSS:

Figure 2: The login screen

The CSS code was used to format the login screen. The same code will be used to format the Hall of Fame Screen at the end of the game. A small nice touch is the shadow.

#loginbg {
     margin-left: auto;
     margin-right: auto;
     text-align: center;
     vertical-align: middle;
     width: 400;
     height: 190;
     background-color: blue;
     color: white;
     font-weight: bold;
     -moz-box-shadow:    5px 5px 10px 0px #000000;
     -webkit-box-shadow: 5px 5px 10px 0px #000000;
     box-shadow:         5px 5px 10px 0px #000000;
}

#login {
     vertical-align: middle;
     color: white;
     font-weight: bold;
}

The check box is used to create a new user. Here I did not create a Registration form as it was not the scope of the assignment. This means that the login form can also be used to register a new user. The first part of the dynamic code is a Java Script function to check that both fields are filled with something before enabling the Submit button. The code shown does this function perfectly:

function checkFilled() {
     var filled = 0;
     var x = document.login.username.value;
     if (x.length > 0) {
           filled ++
     }

     var y = document.login.password.value;
     if (y.length > 0) {
           filled ++
     }

     if (filled == 2) {
           document.login.submit.disabled = false;
     }
     else {
           document.login.submit.disabled = true;
     }
}

Next comes the PHP part. This file contains the PHP code which is used to manipulate the username and password. The first part of the PHP code here is used to initiate a session by using the session_start() function. Then, the PHP code checks if a GET request with "logout" is set. If this condition is true, the session is destroyed. This is used when the server redirects to this page from a logout action.
Then, the PHP code checks if there is a POST request to the server. If this is the case, the login function is called. The function assigns a value to the variables $username and $password from the post values when the form is submitted. The first part is to connect to the database.
          
     $con = mysql_connect("localhost","cannon","cannon");
     if (!$con) {
           die('Could not connect: ' . mysql_error());
     }
     mysql_select_db("cannon_game");

The code above connects to the database server at Localhost with username cannon and password cannon. If the connection is not established, the mysql error is shown. Then, the cannon_game database is chosen. Then, the code checks if the new user check box is checked. If it is not set, the newuser value is set to "undefined".

$sql = mysql_query("Select * from login where username = '".mysql_real_escape_string($username)."';");
     if (($row = mysql_fetch_array($sql)) != 0) {
           if ($password === $row['password']) {
                echo "Password Correct";
                $_SESSION['user']=$username;
                header("Location: ./index.php");
           } else {
                echo "Password Incorrect";
           }
     } else {
           if ($_POST['newuser'] == 'yes') {
                echo "User Does Not Exist, Creating User..";
                $sql = "Insert into login (username,password,highscore) values ('$username','$password','0');";
                if (!mysql_query($sql,$con)) {
                     die('Error: ' . mysql_error());
                }
                echo "</br>";
                echo "User added";
                $_SESSION['user']=$username;
                header("Location: ./index.php");
           } else {
                echo "User Does Not Exist";
           }
     }
     mysql_close($con);
     exit;

The function selects all the records which the user field matches the username. Then, it compares the posted password to the password in the returned record. If there is no match, the page echoes "Password Incorrect".  If there is a match, there is a redirect to the game. If the new user check box is checked, the user is created with the password supplied and a high score of 0, and then it redirects to the game.

Security Feature


Last but not least, the mysql_real_escape_string function removes the threat of a security. It should always be used to make data safe before transmitting. This functions calls MySQL's library function mysql_real_escape_string, which prepends backslashes to these characters: \x00, \n, \r, \, ', " and \x1a.

In the next blog, I will talk more on the High Score System.

No comments:

Post a Comment