15 May 2012

Coursework 2: JavaScript Animation Game Spiced Up – Post 5

Hi there, I'm currently working full blast on coursework 2 and I have finished implementing and testing the 'Sign Up' and 'Remember Me' functions which I had mentioned in my third post on this subject. Therefore I will cover these two function in today's post.


Sign Up Function
Lest start off with taking into consideration new joiners who don't yet have a profile, hence don't have any login details to access the game. For this I created  another page with the required fields the user must fill in and it looks something like this:
Sign Up Form
It's not the prettiest interface, but I'm not really giving much attention to eye candy as I am more interested in the functionality aspect of this project. This situation reminds me of an infographic I saw a while back so I decided to include it in this post :)
Designers VS Developers
So, back to the sign up screen. Validation is pretty much handled the same way as in the login screen, apart from comparing the two password fields to make sure they are the same, therefore I will not go into detail again and stick to what is most interesting.
In this form the user is required to insert a User Login which is essential for it to be unique as he/she will use this as part of their login details. But what if the new user coincidently inputs a user login which is already taken?
I address this issue once the user clicks on the create button, which I will now explain.

Once the create button is clicked a JavaScript function which validates the user input is called and if the validation is a success, this function will call another function named 'redirect()'. Yes you guessed it, this function does the same thing as the one I described in my previous post, but instead sends the full name, user login and the first password field values to another PHP page which I've named 'createNewUser()'.

createNewUser.php:
    
<?php
session_start();

include 'DBConnections.php';

if (isset($_POST['fullName']) && isset($_POST['userID']) && isset($_POST['password'])) {
    $UserID = strtolower($_POST['userID']);

    //check if passed userID is available
    if (mysql_num_rows(checkUserIDAvailability($UserID)) == 0) {//available
        //create new user
        $createUserSQL = "INSERT INTO users (USER_FULL_NAME,USER_NAME,USER_PASSWORD) VALUES('" . $_POST['fullName'] . "','" . $UserID . "','" . $_POST['password'] . "')";
        if (execute($createUserSQL)) {//executes the insert and if true is returned, continues
            //stores user's related data in session variables
            $_SESSION['userName'] = $_POST['fullName'];
            $_SESSION['highScore'] = "0";//by default this is always zero
            $_SESSION['lastBeatenBy'] = "";
            $_SESSION['userID'] = $UserID;
            $_SESSION['Authenticated'] = "yes";

            //redirects to paper toss
            header("Location: PaperToss/paperToss.php");
        }
    } else {// not available
        $_SESSION['error'] = "This User Login is already taken, please input another one";
        $_SESSION['fullName'] = $_POST['fullName'];
        header("Location: signUp.php"); //redirects to signUp
    }
} else {
    header("Location: signUp.php"); //redirects to signUp
}


function checkUserIDAvailability($UserID) {
    $result = execute("SELECT * FROM USERS WHERE USER_NAME = '" . $UserID . "'");
    return $result;
}
?>


Code Breakdown:
As soon as this page is requested, it it makes sure that the session is started and includes the DBConnections.php file I created in my third post on this subject. Then it immediately verifies that the required variables have been posted. Otherwise this request must have been made manually, not via the create button, so it redirects to the sign up page.


If all the variables have been posted, it moves on the check if the user login is available. This is done by calling the function 'checkUserIDAvailability()' which can be seen at the lower end of the code above.
This function makes use of the DBConnections.php 'execute()' function and queries for a record from the users table which has the same user login ($UserID) value. The returned resultset is then stored in '$result' and returns it to the calling statement:

function checkUserIDAvailability($UserID) {
if (mysql_num_rows(checkUserIDAvailability($UserID)) == 0) {//available
    //create new user record   
} else {// not available
    //redirect back to sign up
}


The calling statement is placed in the function 'mysql_num_rows()', this function will return the amount of records present in a resultset, therefore if the row count is not zero, the user login must already be taken, otherwise the  user login is available.


function checkUserIDAvailability($UserID) {
    $result = execute("SELECT * FROM USERS WHERE USER_NAME = '" . $UserID . "'");
    return $result;
}


In case the user login supplied is not available, a session variable named 'error' is created and an explanatory message of what happened is stored in this session variable, this will be used by the sign up page to display to the user. 
Apart from that another session variable named 'fullName' is created and stores the full name the user inputted, this session variable will also be used by the sign up page to populate the Full Name field, so the user will not have to type it again. Finally the user is redirected back to the sign up and the message gets displayed in red:
Sign up page when user login is already taken
On the other hand if the user login is available, crates a new record in the users table with the inputted details:



    
//create new user
$createUserSQL = "INSERT INTO users (USER_FULL_NAME,USER_NAME,USER_PASSWORD) VALUES('" . $_POST['fullName'] . "','" . $UserID . "','" . $_POST['password'] . "')";
//executes the insert and if true is returned, creates required Session 
//variables & redirects to game.
if (execute($createUserSQL)) {
   //stores user's related data in session variables
   $_SESSION['userName'] = $_POST['fullName'];
   $_SESSION['highScore'] = "0";//by default this is always zero
   $_SESSION['lastBeatenBy'] = "";
   $_SESSION['userID'] = $UserID;
   $_SESSION['Authenticated'] = "yes";

   //redirects to paper toss
   header("Location: PaperToss/paperToss.php");
}


After executing the statement, checks if the insert was a success. If so the requires session variables are created and the user is redirected to the game.


Remember Me Function
So, up till now I have only used Session variables and as I have stated before, these are temporary. Therefore to implement a Remember Me function I had to use Cookie variables, as these will be stored on the user's machine and sent along with the request when the user visits my game.
To implement the use of cookies I made the authentication.php page receive an extra variable for the checkbox element.
Once a user is authenticated, if the checkbox value is equal to true I create two cookie variables, one for the login and one for the password and set their value accordingly.
  
if($_POST['rememberMe'] == true){
   setcookie("UserID", $_SESSION['userID']);
   setcookie("UserPW", $_SESSION['userPW']);
}


In the index page (i.e. - the login page), I added a check using PHP code to populate the user login and password fields if the above cookies are sent to the server side:

<?php
//if the user password is set in a cookie, populate the Password field
echo "<input type=\"password\" name=\"password\" title=\"Password\"value=\"";
if (isset($_COOKIE['UserPW'])) {
    echo $_COOKIE['UserPW'];
}
echo "\"/>";
?>


Paper Toss Game Progress
So now, as a recap, my paper tossing game has a fully functional user sign up and login with remember me functionality, thus the task of transforming coursework 1 into a social networking game is taking shape.
By the way do you remember in my previous posts I mentioned that I gave my  game a nice background of a cheering crowd? Well I got in touch with the owner of that image to request permission to use it and, well...he charged me $49 for it. Unfortunately I am not ready to pay that sum of money for a detail of such little importance, therefore to respect others property I changed the background image to an un-copyrighted image, so now it looks like this:


Un-copyrighted background image


1 comment:

  1. I have also made the coursework of JavaScript Animation Games. As a programmer, I say that such types of courseworks always enhance the software programming knowledge of students.

    ReplyDelete