Saturday, May 19, 2012

Coursework 2 - Part 3


Today I am going to talk about the last part of my course work. After nearly finishing my coursework, I got an idea to make the game more interesting. I added a feature that checks if a player beats the current high score, and the current high score was achieved by another player, the game sends an email to the other player to tell him or her that her score was beaten.

Modifying the database

Even though this was not very difficult to do, it took me a whole week to manage to sort it out. First, I added a field in the database of the users to add the email address of the player. This requires the email to be added manually to the database as a new user cannot add an email address in the login form. This was done without because the scope of the login page was not to create a fully featured login form with a registration form.  So, I added an email address to each record in the database. For testing purposes, I inserted my email address in all the fields so that I would not bug other people with my emails.

Checking if the highest score was beaten by another player

Then, I started to modify the function which compares the high scores. After opening the connection with the database, I made a query to obtain the username, the high score and the email of the person who is at the top of the hall of fame.  The query which I used is shown below:

select username, highscore, email
from cannon_game.login    
order by highscore desc limit 1;

The record obtained is inserted into the variable $row and from it I obtained a value for the $topuser, $topscore and $topemail, which are the details of the player with the highest score in the hall of fame. Then an if statement checks if the current score is larger than the $topscore value from the database. If the score is higher than the topscore, the difference is calculated. Then, another if statement checks if the current player is the topuser. If it is not the same user, then it means that the person who was first, now moves to second place. Then, a function called email is called and it is passed the values for topuser, topemail and the score difference. Then the function continues to update the scores accordingly like it used to do before.

Testing this function

Knowing that emailing would not work immediately, I tested this function a bit primitively, using echo. I tested by using different users to play the game and trying to achieve a better score every time. I was not playing the game to obtain the highest possible score. I tried to keep scores low so I would not have to reset the scores from the database because I would not be able to beat them. By echoing the variables values I knew that the function to check if the high score was beaten by another player was working great.

Email function

I created the email function and I passed to it the variables $topuser, $topemail and $scoredifference. To send emails you need a to address to send emails to, a from address, a subject and a body. The to email was obtained from the database and passed to the function. I used my personal email as the from email address. Then I crafted a subject and a body message using the user name and the score difference. The code below shows the first part of the email function:

     $to = $topemail;
     $from = "danielborgmt@gmail.com";
     $subject = ucwords($topuser).", be careful!!";
     $body = ucwords($topuser).", your score was beaten by "                   .$scoredifference." points!! Make sure to beat his score to          stay in the first place!!!";

The function ucwords() is used to capitalize the first letter of the string passed to it. Then you need an SMTP server to be able to send emails. This gave me a lot of problems and took me nearly a week to solve. I talked about this in my previous blog. After trying a lot of solutions, I managed to find a working script which worked nearly immediately. The script was a PEAR extension and I used the following code to be able to use it:

     $er = error_reporting(0);
     require_once "Mail.php";

SMTP Server Settings

The error_reporting(0) is used to hide errors for using methods which were not called using a STRICT method. This was done at the top of the php file. After enabling SSL on my web server, I added the details of my Gmail account to use Gmail's SMTP server. Then I called the function to send the email to the details of the player who was first using my Gmail SMTP server. The code is shown below:

     $host = "ssl://smtp.gmail.com";
     $port = "465";
     $username = "danielborgmt";
     $password = "mypassword";
     $headers = array ('From' => $from, 'To' => $to, 'Subject' =>                         $subject);
     $smtp = Mail::factory('smtp', array ('host' => $host,'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
     $mail = $smtp->send($to, $headers, $body);
          
     if (PEAR::isError($mail)) {
          echo("<p>" . $mail->getMessage() . "</p>");
     }

This code allowed me to send emails properly to the player who lost the first place.


Figure 1: Sample Email from PHP Script


Figure 2: Email details

This concludes my second coursework.

Wednesday, May 16, 2012

PHP and Sending Emails


As we know, send emails from PHP scripts can sometimes be vital. We see this in practice nearly every day, especially with registration forms. Most of the times, when we register on a new website, we receive an email from the company which requires us to follow a link to verify that it was a person who submitted the request. This is also the case when we are resetting a password. We receive an email with a random password or to follow a link to create a new password.

Several things exist to send emails from PHP. Among them we find the normal mail() function, the sendmail application, and other scripts which allow us to send emails.

SMTP

To send an email, the SMTP (Simple Mail Transfer Protocol) Protocol is used. This protocol uses port 25 for communication. This means that port 25 must not be blocked on our firewall in the first place. Several forms of SMTP servers exist, and we might not have one running on our local machine. There are several setups which we might come across:

  • SMTP Server without authentication
  • SMTP Server with authentication
  • SMTP Server with authentication and SSL


SMTP Servers without authentication are become rarer, due to the fact that these are many times used by spammers and thus were blacklisted by ISPs as spamming engines. SMTP Servers with authentication require a username and a password to allow mail to pass through. Many times, they use the username and password used for the incoming mail server. SSL is a form of encryption which increases the level of security as the messages are not sent in plain text format.

Gmail

One good common SMTP server is the Gmail SMTP Server. This allows users who have an account with Gmail to authenticate and send emails through the server. Gmail uses SSL and this means that it uses port 465 instead of port 25. SSL is not always enabled in PHP, so it is useful to turn it on.

Enabling SSL in PHP

SSL is required by Gmail and other SMTP servers using SSL. This means that we need to enable it in PHP. There are a few easy steps to enable SSL in XAMPP which I am using for my testing environment. The first thing is to stop the Apache service. Then copy libeay32.dll and ssleay32.dll from the php directory to the apache/bin directory, overwriting the existing copies. Then, make sure that there is an entry for the open SSL extension in the php.ini file. The entry should be like this: extension=php_openssl.dll, without the semicolon in the front. Then start the Apache service again. The service should start with SSL support.

PHP Mail Function

The PHP mail() function is a function used to send emails. This takes 5 parameters:

  • to
  • subject
  • message
  • headers (optional)
  • parameters (optional)


This function uses the SMTP configuration found in the php.ini file. This mainly consists of SMTP server, smtp_port, sendmail_from and sendmail_path. The SMTP server takes the address of the SMTP server, the smtp_port takes the port which the SMTP is configured to work on. The sendmail_from indicated the email address which is shown as the from address, while the sendmail_path is the installation path of the sendmail application. The code snippet below shows a sample of the mail function

<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>

PHP Scripts

Several additional scripts exist apart from the mail() function in PHP. Several people and groups of people went a step forward and created complex mail functions to add more features to this important task in PHP. During my research to send emails from PHP, due to the fact that mail() function was not working, I found many advanced projects. Each project had its own way to send emails and its own classes which needed importing to the actual PHP function which I was using. As a matter of fact, I ended up using one of these methods.

Pear and Mail() Script

After a lot of problems with other functions and setups, I managed to find a working script. I am not saying in any way that all of the other scripts contained bugs, far from it, but I did not manage to make them work. I used a Pear extension which actually managed to send emails. I downloaded version 1.2.0 of their scripts which I placed in the directory of my PHP file. I imported the file in my PHP file and then was able to call the method. After setting up values for to, from, subject and body, I was able to setup the server part in the code and then call the send function, as shown below:

            $er = error_reporting(0);
     require_once "Mail.php";

$host = "ssl://smtp.gmail.com";
$port = "465";
$username = "danielborgmt";
$password = "mypassword";
$headers = array
     ('From' => $from,
     'To' => $to,
     'Subject' => $subject);
$smtp = Mail::factory('smtp', array
     ('host' => $host,
     'port' => $port,
     'auth' => true,
     'username' => $username,
     'password' => $password));
$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
     echo("<p>" . $mail->getMessage() . "</p>");
}

The first line shows a function which disables errors caused by not following the strict procedures. This function's result ended up in my testing mailbox :)

My Issues with PHP and Sending Emails

I experienced several issues when setting up this application. Most of them were errors due to not understanding exactly how the PHP sendmail function works, and other small issues with settings for the SMTP servers. The list below shows a number of issues I had:

  • did not properly setup php.ini and incorrect path for sendmail
  • incorrect settings in sendmail.ini
  • incorrect mail server address, incorrect username format, incorrect password
  • incorrect server port
  • using SMTP server with Authentication without providing a username and password
  • disabled SSL
  • closed ports on the Windows Firewall


After a whole week of struggling and research, I managed to overcome these difficulties. The picture below shows a sample email I sent from PHP.


Figure 1: Sample Email from PHP Script

Figure 2: Email details

Wednesday, May 9, 2012

More on PHP


PHP and MySQL

MySQL is the most common open-source database system. It is very popular across the globe and has very good integration with PHP. Data is stored in tables within a particular database. Tables are in turn made up of rows and columns.  SQL on the other hand is a query language used to interact between an application and the database. Each type of database has its particular SQL language, so it can be a bit tricky to work with different database servers. For the sake of this blog, I will only speak about MySQL.
The first thing to do when interfacing between PHP and MySQL is to open a connection. This can be done using the mysql_connect() function which takes the servername, the username and the password as parameters, among others. Most of the times, this connection is stored in a string variable, as shown below:

<?php
      $con = mysql_connect("localhost","peter","abc123");
      if (!$con)
      {
            die('Could not connect: ' . mysql_error());
      }
     
      // some code
      mysql_close($con);
?>

The last line before the closing tag shows the connection being closed. This is an important step because malicious users can make use of open connections. Also, open connections will increase the load on the server. The code in the if statement is executed if the connection fail. The mysql_error() shows the exact reason for the failure. This is very important to troubleshoot the issue.

All the queries work this same from PHP as if they were executed in MySQL Workbench, so I will not go into INSERT and UPDATE statements.

Selecting Data

Although the SQL command for selecting data is still the same, the results returned need to be manipulated to be used for the developer's needs. The code below is to select all the rows in the table and display them one after the other.

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }

The first line above shows the code used to select a Database from the server. This is important because a database server might have more than one database. The result variable holds the data returned by the mysql_query () function. The function mysql_fetch_array() returns the next row in the recordset. The while loop is used to loop through all the records in the recordset. Each row is an array of columns and the value of each row can either be accessed by the field name or by the index. $row['0'] and $row['FirstName'] will return the same value.

Show Results in HTML

The results can then be formatted by also echoing the HTML tags. This can be seen in the example below:
echo "<table border='1'>
<
tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

This will create an HTML table dynamically with all the records in the table.

PHP and ODBC

ODBC is an API which allows PHP to connect to a data source.  With such a connection, PHP can connect to any database or computer on the network. In this example I will setup a connection with a MS Access Database. To create an ODBC connection to a MS Access Database, these steps have to be followed:

  1. Open the Administrative Tools icon in your Control Panel.
  2. Double-click on the Data Sources (ODBC) icon inside.
  3. Choose the System DSN tab.
  4. Click on Add in the System DSN tab.
  5. Select the Microsoft Access Driver. Click Finish.
  6. In the next screen, click Select to locate the database.
  7. Give the database a Data Source Name (DSN).
  8. Click OK.

This process required access to the location of the database. Next, we have to setup a connection to the ODBC. the odbc_connect() function is used to accomplish this task. This function takes 4 parameters: data source name, username, password and optional cursor type.  The code below shows this:

$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);

Retrieving Records

The function odbc_fetch_row() function can be used to return records from the result-set. This function takes the OSBC result identifier and an optional row number. To read fields from a record, the odbc_result() function is used and this function takes the ODBC result identifier and a field number or name.

<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
  {exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
  {exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
  {
  $compname=odbc_result($rs,"CompanyName");
  $conname=odbc_result($rs,"ContactName");
  echo "<tr><td>$compname</td>";
  echo "<td>$conname</td></tr>";
  }
odbc_close($conn);
echo "</table>";
?>

The php code above shows the whole process using a MS Access Database and ODBC instead of MySQL. Last but not least, the connection will be closed. As we can see, the code is very similar to the mysql_fetch_array() function used before.

Getting started with PHP


PHP is a server-side scripting language. Before starting to learn PHP, one should already have basic understanding of HTML or XHTML and of JavaScript. PHP stands for PHP: Hypertext Preprocessor. It is a server-side scripting language, similar to ASP. This means that scripts are run on a server and the client gets the result of the script execution. PHP supports a large number of databases as well, such as MySQL, Oracle, and more. The biggest advantage of PHP is that it is an open source project and it is free to download and use.

To start developing with PHP, one needs access to a web server with PHP support. The two most popular are Apache and IIS. Several options exist on how to implement your server setup. For testing, many people prefer to use XAMPP, which I mentioned in another blog. XAMPP comes ready with all the features required installed. However, it is not recommended to use XAMPP on production systems. Also, for most of the functions, MySQL is also required. This is also available for free.

With PHP up and running, it is fairly simple to get started. PHP code is written between the opening tag and the closing tag.

                <?php
           echo "Hello World";
     ?>

Also, for the code to execute on the server, the file extension must be .php, even though this file might include HTML and JavaScript. Most of the times, we want the script to output something to the screen. This might be in the form of informative messages, such as "Hello World", and it can also be to generate HTML code to populate a table with results from a database, such as the code snippet below:

                <?php
          while (($row = mysql_fetch_array($sql))) {
print("<tr><td>".(ucwords($row[0]))."</td><td>".$row[1]."</td></tr>");
          }
     ?>

The code above inserts the row tags, <tr>, and the column tags, <td>, together with the information to be inserted in the table. As you might noted, there are two methods for outputting messages: echo and print.

Variables in PHP

Variables are used in PHP similarly to other programming languages. Variables start by the $ sign in front of the name. Variable named cannot start with a number or special character and they are case sensitive. Variables in PHP can have  different variable scopes: local, global, static, and parameter.
Local Scope variables are declared within a function and can only be accessed within that function. Global Scope variables are any variables declared outside a function and these can be accessed from anywhere. To access them from functions, the keyword global must be used. Static Scope variables are variables which are not deleted and these are declared by using the keyword static. Parameters are local variables whose value is passed to the function by the calling code.

String Operations and Functions

In PHP there is only one string operator. The is the concatenation operator (.). This is used to put two string values together forming one string. The code below shows two strings being concatenated:

<?php
     $txt1="Hi, my name is ";
     $txt2="Daniel Borg!";
     echo $txt1 . " " . $txt2;
?>

The code above will output "Hi, my name is Daniel Borg!". Several functions related to strings exist to facilitate the life of a PHP developer. These include strlen() which returns the length of the string and the strpos() which returns the position of a character within the string specified.

PHP, like all other languages, has its own set of arithmetic, assignment, incrementing, and decrementing operators. It also has some array operators which are shown below:

Operator
Name
Description
x + y
Union
Union of x and y
x == y
Equality
True if x and y have the same key/value pairs
x === y
Identity
True if x and y have the same key/value pairs in the same order and of the same types
x != y
Inequality
True if x is not equal to y
x <> y
Inequality
True if x is not equal to y
x !== y
Non-identity
True if x is not identical to y

Forms

These are variables which are used to retrieve information from forms. THe code below shows a very simple form:

<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

</body>
</html>

When a user fills out this form and submits it, the data is sent to the PHP file welcome.php. The welcome.php code is show below:

<html>
<body>

Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

The output of the page would be:

                Welcome Daniel!
                You are 24 years old.

Ideally, the forms will have some validation mechanism to remove security threats and to control the input of data.

$_GET Variable

The $_GET variable is used to collect values in a form with method="get". The information passed when the GET method is used is shown in the address bar, making it unsafe to use for login screens. It is also limited in the amount of information which can be sent. The code below shows a form using the GET method:

<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

When the submit button is clicked, the URL sent to the server will look like this:

yourdomain.com/welcome.php?fname=Daniel&age=24

The code in the welcome.php can make use of the values passed by using the $_GET variables as shown below:

                Welcome <?php echo $_GET["fname"]; ?>.<br />
      You are <?php echo $_GET["age"]; ?> years old!

Which will return:

      Welcome Daniel.
      You are 24 years old!

The get method should not be used when information is sensitive and for very large variable values.

$_POST Variable

The $_POST variable is used to collect values from forms sent with method="post". Information sent using the post method is invisible to others. The maximum size for the POST method is 8MB but this can be changed in the php.ini file (post_max_size). The syntax is identical to the $_GET. The disadvantage of the post method is that the page cannot be bookmarked.

$_REQUEST

This variable contains the values of the $_GET, $_POST, and $_COOKIE. It can be used to collect form data sent with both GET and POST methods.

Monday, May 7, 2012

Coursework 2 - Part 2


After the login part of the game, the user can now play. When the page loads, there are additional items which were not there before. The new features are the welcome message at the top left of the screen, below which we find the current score.  At the top right of the game there is a counter going down. When the player hits the ship, the value of the counter going down is added to the current score at the right of the screen. The game can end in two ways. The first method is when the counter goes down to 0 and the other method is when the ship reaches the cannon.

Figure 1: The Layout of the Game

Also, on page load, there is a table with the high scores called the hall of fame. The hall of fame is loaded into a div called highscores to the right of the game.

                <div id="highscores"></br>Hall of Fame</br></br>
          <table>
                <thead>
                     <tr>
                     <th>Username</th><th>Highest Score</th>
                     </tr>
                </thead>
                <tbody>
                     <?php getHighScores();?>
                </tbody>
          </table>
     </div>

 The code above shows how the hall of fame is generated. The body of the table is generated from the PHP function getHighScores(). The code below shows the code generating the body of the table:

$sql = mysql_query("SELECT username, highscore FROM cannon_game.login order by highscore desc, username limit 10;");

while (($row = mysql_fetch_array($sql))) {
print("<tr><td>".(ucwords($row[0]))."</td><td>".$row[1]."</td></tr>");
}

The code above prints the HTML code together with the values returned from the query. It truncates the result to the top 10 scores. Here we are using the function ucwords() to capitalize the username.
Update the Score
The next part of this assignment is to update the high score when the game is over. When the game is over, the file comparehighscore.php is called passing the playerscore. This can be seen in the image below:

Figure 2: Passing the score to the PHP function

The username is obtained from the session. The comparehighscore.php then calls a function with the user and the score. The functions gets the score for the current user. Then, it compares the current score to the score obtained from the database. If the current score is larger than the score in the database, the score of the user is inserted into the database. This is shown in the code below:

$sql = mysql_query("SELECT username, highscore FROM cannon_game.login where username='".mysql_real_escape_string($username)."';");

if (($row = mysql_fetch_array($sql))) {
$oldscore = $row[1]+0;
if ($score > $oldscore) {
mysql_query("UPDATE login SET highscore='".mysql_real_escape_string($score)."' where username='".mysql_real_escape_string($username)."';");
}
}

Logout Function

Another part is the logout function. This is a very simple function that unsets the session and redirects the page to the login.

     function logout() {
           unset($_SESSION['user']);
           header("Location: ./login.php");
     }

Hall of Fame

When the game is over, the game redirects to the Hall of Fame Screen. The style is similar to the login screen, except for the size. The hall of fame lists the top 10 high scores, along with the Username. The screen has two buttons, Return to Game and Logout. Return to the game redirects to the game, while keeping the session. This means that the player can try again. By pressing the logout button, the player can logout and the game redirects to the login screen. This will allow another player to play the game. Below is a shot of the Hall of Fame with the sample data.

Figure 3: Hall of Fame with the sample data.

In the next part of the blog I will talk about some more features.

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.