Setting up a leaderboard using PHP/MySQL

Games are more fun when there is a leaderboard of high scores that the players have achieved. Even single player games can communicate to a shared web-based leaderboard. This recipe includes both, the client side (Unity) code, as well as the web-server side (PHP) scripts to set and get the player scores from a MySQL database.

Setting up a leaderboard using PHP/MySQL

Getting ready

This recipe assumes that you either have your own web hosting, or are running a local web server and a database server, such as XAMPP or MAMP. Your web server needs to support PHP, and you also need to be able to create the MySQL databases.

All the SQL, PHP, and C# scripts for this recipe can be found in the 1362_10_07 folder.

Since the scene contains several UI elements and the code of the recipe is the communication with the PHP scripts and SQL database, in 1362_10_07 folder, we have provided a Unity package called PHPMySQLeaderboard, containing a scene with everything set up for the Unity project.

Note

If you are hosting your leaderboard on a public website, you will change the names of the database, database user and password for reasons of security. You should also implement some form of secret game code, as described in the There's more… section.

How to do it...

To set up a leaderboard using PHP and MySQL, do the following:

  1. On your server, create a new MySQL database named cookbook_highscores.
  2. On your server, create a new database user (username=cookbook, password=cookbook) with full rights to the database that you just created.
  3. On your server, execute the following SQL to create the database table called score_list:
    CREATE TABLE `score_list` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `player` varchar(25) NOT NULL,
      `score` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
  4. Copy the provided PHP script files to your web server:
    1. index.php
    2. scoreFunctions.php
    3. htmlMenu.php
  5. Create a new 2D Unity project and extract the Unity package called PHPMySQLeaderboard.
  6. Run the provided scene, and click on the buttons to make Unity communicate with the PHP scripts that have access to the high score database.

How it works...

The player's scores are stored in a MySQL database. Access to the database is facilitated through the PHP scripts provided. In our example, all the PHP scripts were placed in the web server root folder for a local Apache webserver. So, the scripts are accessed via http://localhost:8888/. However, since URL is a public string variable, this can be set before running to the location of your server and site code.

All the access is through the PHP file called index.php. There are five actions implemented, and each is indicated by adding the action name at the end of the URL (this is the GET HTTP method, which is sometimes used for web forms. Take a look at the address bar of your browser next time you search Google for example). The actions and their parameters (if any) are as follows:

  • action = html: This action asks for HTML text listing all player scores to be returned. This action takes no parameters. It returns: HTML text.
  • action = xml: This action asks for XML text listing all player scores to be returned. This action takes no parameters. It returns: XML text.
  • action = reset: This action asks for a set of default player name and score values to replace the current contents of the database table. This action takes no argument. It returns: the string reset.
  • action = get: This action asks for the integer score of the named player that is to be found. It takes parameters in the form player = matt. It returns: the score integer.
  • action = set: This action asks for the provide score of the named player to be stored in the database (but only if this new score is greater than the currently stored score). It takes parameters in the form player = matt, score = 101. It returns: the score integer (if the database update was successful), otherwise a negative value (to indicate that no update took place).

There are five buttons in the Unity scene (corresponding to the five actions) which set up the corresponding action and the parameters to be added to the URL, for the next call to the web server, via the LoadWWW() method. The OnClick actions have been set up for each button to call the corresponding methods of the WebLeaderBoard C# script of the Main Camera.

There are also three UI Text objects. The first displays the most recent URL string sent to the server. The second displays the integer value that was extracted from the response message that was received from the server (or a message as "not an integer" if some other data was received). The third UI Text object is inside a panel, and has been made large enough to display a full, multi-line, text string, received from the server (which is stored inside the textFileContents variable).

The three UI Text objects have been assigned to the public variables of the WebLeaderBoard C# script for the Main Camera. When the scene first starts, the Start() method calls the UpdateUI() method to update the three text UI elements. When any of the buttons are clicked, the corresponding method of the WebLeaderBoard method is called, which builds the URL string with parameters, and then calls the LoadWWW() method. This method sends the request to the URL, and waits (by virtue of being a coroutine) until a response is received. It then stores the content, received in the textFileContents variable, and calls the UpdateUI() method.

There's more...

The following sections will fine-tune and customize this recipe for you:

Extracting the full leaderboard data as XML for display within Unity

The XML text that can be retrieved from the PHP web server provides a useful method for allowing a Unity game to retrieve the full set of the leaderboard data from the database. Then, the leaderboard can be displayed to the user in the Unity game (perhaps, in some nice 3D fashion, or through a game-consistent GUI).

Using the secret game codes to secure your leaderboard scripts

The Unity and PHP code that is presented illustrates a simple, unsecured web-based leaderboard. To prevent players hacking into the board with false scores, it is usual to encode some form of secret game code (or key) into the communications. Only update requests that include the correct code will actually cause a change to the database.

The Unity code will combine the secret key (in this example, the string called harrypotter) with something related to the communication—for example, the same MySQL/PHP leader board may have different database records for different games that are identified with a game ID:

// Unity Csharp code
string key = "harrypotter"
string gameId = 21;
string gameCode = Utility.Md5Sum(key + gameId);

The server-side PHP code will receive both the encrypted game code, and also the piece of game data that is used to create that encrypted code (in this example, the game ID and MD5 hashing function, which is available in both, Unity and in PHP). The secret key (harrypotter) is used with the game ID to create an encrypted code that can be compared with the code received from the Unity game (or whatever user agent or browser is attempting to communicate with the leaderboard server scripts). The database actions will only be executed if the game code created on the server matches that send along with the request for a database action.

// PHP – security code
$key = "harrypotter"
$game_id =  $_GET['game_id'];
$provided_game_code =  $_GET['game_code'];
$server_game_code = md5($key.$game_id);

if( $server_game_code == $provided_game_code ) {
  // codes match - do processing here
}

See also

Refer to the following recipe for more Information:

  • Preventing your game from running on unknown servers in Chapter 11, Improving Games With Extra Features and Optimization
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.139.172