- User Login
- User registration
- Score Keeping & score boards
- Notifications
Therefore I will be posting 4 more posts which will cover these in the following weeks.
For this post I will be concentrating on the User Login function, so here goes!
User Login - Subtasks
As I have always said, it's best to divide your tasks into multiple subtasks, I have divided mine like so:
- Create a simple User Login screen using simple HTML
- How to validate user input
- How to store the user data
- Decide where the user authentication should take place (client-side or server-side) and how.
Create a simple User Login screen
This is the easiest task of them all, so I will not be going into much detail on how to do this, you should already have good knowledge of HTML by now.
The code below will create my User Login screen, but it will not do anything for know.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Paper Tossing Login</title>
</head>
<body>
<h2 style="color: #0000CC">Paper Tossing Login</h2>
<form name="loginForm">
<table>
<tr>
<td>User ID:</td>
<td><input type="text" name="userID" title="User ID"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" title="Password"/></td>
</tr>
<tr>
<td><input type="submit" value="Login" name="login"/></td>
<td><input type="button" value="Cancel" name="cancel"/></td>
</tr>
</table>
</form>
</body>
</html>
The HTML code above is simply creating a form element and stores; a text field for the User ID, a password field for the user's password, a submit button and a cancel button within a table inside the form. This should look like this:
| Initial Login Screen |
Now before I move on, I would like the cancel button to remove any text from the input fields and set the focus on the User ID input field.
Instantly, two methods come to mind:
- Either programmatically refresh the page.
- Use JavaScript
Obviously I do not want to refresh the page, so JavaScript is the way to achieve this.
I started out by inserting a script tag in the header element and defined its type as 'text/javascript'. Then I created a function named 'resetFrom()' and used to following code:
function resetForm(){
document.loginForm.userID.value = "";
document.loginForm.userID.focus();
document.loginForm.password.value = "";
}
This code uses the DOM object to reference the mentioned fields by their name, for example:
document.loginForm.userID.value = "";
First calls the DOM, then the form element (named: 'loginForm'), then the User ID field (named: 'userID') and finally stores an empty string in the element's value attribute.
In the cancel button element, I then call the function when the user clicks the button by setting its 'onClick' attribute to 'resetForm()' like so:
<input type="button" value="Cancel" name="cancel" onclick="resetForm();"/>
Validate User Input
Now that I have created my login screen, the next step I want to take is to validate the user's input by making sure that a value has actually been entered.
The first decision I had to take was where should it be handled; on the server-side or on the client-side?
It's good practice to take care of input validations on the client-side as this will improve server load and does not require any communication between client and server.
I set off implementing this using JavaScript by introducing a new function named 'validate()' and set the Login button to call this function once it gets clicked via its 'onClick' attribute. The code for this can be seen below:
function validate(){
if((document.loginForm.userID.value == "")&&(document.loginForm.password.value == "")){
alert("User ID and Password cannot be empty");
}else if(document.loginForm.password.value == ""){
alert("Password cannot be empty");
}else if(document.loginForm.userID.value == ""){
alert("User ID cannot be empty");
}
}
Again, I am using the DOM to access the input elements' value and this time I'm checking if they are empty. If so I display an message box with the appropriate message.
How to store the user data
Obviously there is more than one way to achieve this, to name a few:
Now that I have created my login screen, the next step I want to take is to validate the user's input by making sure that a value has actually been entered.
The first decision I had to take was where should it be handled; on the server-side or on the client-side?
It's good practice to take care of input validations on the client-side as this will improve server load and does not require any communication between client and server.
I set off implementing this using JavaScript by introducing a new function named 'validate()' and set the Login button to call this function once it gets clicked via its 'onClick' attribute. The code for this can be seen below:
function validate(){
if((document.loginForm.userID.value == "")&&(document.loginForm.password.value == "")){
alert("User ID and Password cannot be empty");
}else if(document.loginForm.password.value == ""){
alert("Password cannot be empty");
}else if(document.loginForm.userID.value == ""){
alert("User ID cannot be empty");
}
}
Again, I am using the DOM to access the input elements' value and this time I'm checking if they are empty. If so I display an message box with the appropriate message.
How to store the user data
Obviously there is more than one way to achieve this, to name a few:
- Text files
- XML files
- Database tables
All of these are good options, but for the sake of already covering server-side database usage in my PHP post last week, I decided I wanted to use XML, as I once posted about the subject but I never really used it in practice.
Keeping in mind that I will implement scoring and notifications in the near future, I made the following list of details I should store about each user:
- User Name
- User ID
- User Password
- High Score
- Placing
- Last Beaten By
The first four are obvious enough, but I would like to explain the last two.
Placing:
I want dedicate a page as a score board.
Last Beaten By:
I want to display to the users which other person beat his/her top score once they are logged in. Therefore I plan on storing the other person's name under Last Beaten By.
To get the ball rolling on this matter I created the above XML document and inserted 3 dummy users. I have pasted this XML below:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<user>
<userName>Clifford</userName>
<userID>Cliff</userID>
<userPW>1234</userPW>
<highScore>20</highScore>
<placing>1</placing>
<lastBeatenBy></lastBeatenBy>
</user>
<user>
<userName>Wayne</userName>
<userID>Wayne</userID>
<userPW>5678</userPW>
<highScore>15</highScore>
<placing>2</placing>
<lastBeatenBy>Clifford</lastBeatenBy>
</user>
<user>
<userName>Rebecca</userName>
<userID>Becca</userID>
<userPW>1234</userPW>
<highScore>0</highScore>
<placing>3</placing>
<lastBeatenBy>Clifford</lastBeatenBy>
</user>
</root>
To get the ball rolling on this matter I created the above XML document and inserted 3 dummy users. I have pasted this XML below:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<user>
<userName>Clifford</userName>
<userID>Cliff</userID>
<userPW>1234</userPW>
<highScore>20</highScore>
<placing>1</placing>
<lastBeatenBy></lastBeatenBy>
</user>
<user>
<userName>Wayne</userName>
<userID>Wayne</userID>
<userPW>5678</userPW>
<highScore>15</highScore>
<placing>2</placing>
<lastBeatenBy>Clifford</lastBeatenBy>
</user>
<user>
<userName>Rebecca</userName>
<userID>Becca</userID>
<userPW>1234</userPW>
<highScore>0</highScore>
<placing>3</placing>
<lastBeatenBy>Clifford</lastBeatenBy>
</user>
</root>
User Authentication (Where & How)
So know I have established that I will be using XML as my data source, therefore to authenticate my users I must retrieve data from this file in order to authenticate them.
After doing some research I learnt about two ways of doing this, either by using AJAX technology via XmlHttpRequests and XmlHttpResponse or by using PHP.
These two options are worlds apart as the AJAX method will be sent from the client-side and PHP will take place on the server-side.
Since I already posted a bit about PHP, I opted to use this method and further improve my knowledge on the subject.
Therefore I created a PHP file and named it 'authentication.php'. I will now take you step by step through the code:
1st - Verify that the required inputs have been posted to this file
//checks if the userID and password values have been posted with the file request
if ((isset($_POST['userID']) && isset($_POST['password'])) && (trim($_POST['userID'] != "") && trim($_POST['password'] != ""))) {
//stores the inputs in session variables
$_SESSION['userID'] =strtolower( $_POST['userID']);
$_SESSION['userPW'] = $_POST['password'];
If all the conditions are met, the user input is stored in session variables via the associative array $_SESSION this is also known as a 'superglobal' meaning it exists in every scope and you don't need the to use the key word global in front of it in order to reference it.
2nd - Authenticate the user by looking up the inputs in the XML file
For this I created a function named 'authUser()' which requires two parameters; '$userID' and '$password' and returns a boolean value.
/**
*Looks up the userSource.xml for the userID and password provided and returns a boolean
*accordingly.
* @param type $userID
* @param type $password
* @return boolean
*/
function authUser($userID, $password) {
//load XML file
$xml = simplexml_load_file("userSource.xml");
//loop through every <user> element in the XML file
foreach ($xml->xpath('//user') as $user) {
if ($userID == (string) $user->userID) {//userID matches
//checks if inputted password matches current user's registered password
if ($password == (string) $user->userPW) {//userPW matches therefore user authenticated!
//stores user's related data in session variables
$_SESSION['userName'] = $user->userName;
$_SESSION['highScore'] = $user->highScore;
$_SESSION['lastBeatenBy'] = $user->lastBeatenBy;
$_SESSION['placing'] = $user->placing;
$_SESSION['userID'] = $userID;
$_SESSION['userPW'] = $password;
return TRUE;
}else{
return FALSE;
}
}
}
return FALSE;
}
The above code, loads the XML file containing all the user data and loops through all the <user> elements.
On every iteration, checks if the current <user> element's respective UserID matches the one received as a parameter and if a match is found, compares the respective UserPW values as well.
If these match, the user's data is stored in session variables and the function returns a TRUE value, else returns FALSE.
If the looping ends, without having found a matching UserID, the function returns a FALSE value.
3rd - Act according to authUser() returned value
//athenticates the user
$authUser = authUser($_SESSION['userID'], $_SESSION['userPW']);
//acts according to the returned result
if ($authUser) {
header("Location: PaperToss/paperToss.html"); //redirects to paper toss
$_SESSION['Authenticated'] = TRUE;
} else {
$_SESSION['Authenticated'] = FALSE;
header("Location: index.php"); //redirects to login
}
Here I am calling the function I described in the previous section and storing the returned value in '$authUser'.
Then I use this value in an IF statement which dictates whether to redirect the user to the paper toss game and mark him/her as Authenticated = TRUE or to redirect the user back to the login screen and mark him/her as Authenticated = FALSE.
Conclusion
So that's it for this first post on coursework 2, as a recap we covered the following topics:
After doing some research I learnt about two ways of doing this, either by using AJAX technology via XmlHttpRequests and XmlHttpResponse or by using PHP.
These two options are worlds apart as the AJAX method will be sent from the client-side and PHP will take place on the server-side.
Since I already posted a bit about PHP, I opted to use this method and further improve my knowledge on the subject.
Therefore I created a PHP file and named it 'authentication.php'. I will now take you step by step through the code:
1st - Verify that the required inputs have been posted to this file
//checks if the userID and password values have been posted with the file request
if ((isset($_POST['userID']) && isset($_POST['password'])) && (trim($_POST['userID'] != "") && trim($_POST['password'] != ""))) {
//stores the inputs in session variables
$_SESSION['userID'] =strtolower( $_POST['userID']);
$_SESSION['userPW'] = $_POST['password'];
If all the conditions are met, the user input is stored in session variables via the associative array $_SESSION this is also known as a 'superglobal' meaning it exists in every scope and you don't need the to use the key word global in front of it in order to reference it.
2nd - Authenticate the user by looking up the inputs in the XML file
For this I created a function named 'authUser()' which requires two parameters; '$userID' and '$password' and returns a boolean value.
/**
*Looks up the userSource.xml for the userID and password provided and returns a boolean
*accordingly.
* @param type $userID
* @param type $password
* @return boolean
*/
function authUser($userID, $password) {
//load XML file
$xml = simplexml_load_file("userSource.xml");
//loop through every <user> element in the XML file
foreach ($xml->xpath('//user') as $user) {
if ($userID == (string) $user->userID) {//userID matches
//checks if inputted password matches current user's registered password
if ($password == (string) $user->userPW) {//userPW matches therefore user authenticated!
//stores user's related data in session variables
$_SESSION['userName'] = $user->userName;
$_SESSION['highScore'] = $user->highScore;
$_SESSION['lastBeatenBy'] = $user->lastBeatenBy;
$_SESSION['placing'] = $user->placing;
$_SESSION['userID'] = $userID;
$_SESSION['userPW'] = $password;
return TRUE;
}else{
return FALSE;
}
}
}
return FALSE;
}
The above code, loads the XML file containing all the user data and loops through all the <user> elements.
On every iteration, checks if the current <user> element's respective UserID matches the one received as a parameter and if a match is found, compares the respective UserPW values as well.
If these match, the user's data is stored in session variables and the function returns a TRUE value, else returns FALSE.
If the looping ends, without having found a matching UserID, the function returns a FALSE value.
3rd - Act according to authUser() returned value
//athenticates the user
$authUser = authUser($_SESSION['userID'], $_SESSION['userPW']);
//acts according to the returned result
if ($authUser) {
header("Location: PaperToss/paperToss.html"); //redirects to paper toss
$_SESSION['Authenticated'] = TRUE;
} else {
$_SESSION['Authenticated'] = FALSE;
header("Location: index.php"); //redirects to login
}
Here I am calling the function I described in the previous section and storing the returned value in '$authUser'.
Then I use this value in an IF statement which dictates whether to redirect the user to the paper toss game and mark him/her as Authenticated = TRUE or to redirect the user back to the login screen and mark him/her as Authenticated = FALSE.
Conclusion
So that's it for this first post on coursework 2, as a recap we covered the following topics:
- Creating a user login page
- Validate user input with JavaScript
- Reading from an XML file with PHP
- Authenticating a user using PHP and session variables
In my next post regarding coursework 2 I will cover how to make a new user registration page.
No comments:
Post a Comment