Saturday, May 12, 2012

Sharing the JavaScript Score with PHP

A short post. I added some code to the game so that it can transport the score to the PHP environment.

I decided to use the simplest method possible: I will redirect to a PHP page, and pass the score by placing it in the URL, thus making it a GET variable in PHP.

window.location.href=
"processScore.php?score="+totalScore;

Because of the security issues with this, the PHP script will quickly transfer the GET variable to a SESSION variable, and redirect again.

<?php
//check if the GET variable exists
if ((!empty($_GET)) && ($_GET['score'] > 0)) {
 if (!isset($_SESSION)) {
  session_start();
 }
 
 $_SESSION['user_score'] = $_GET['score'];
 header("Location:finalScore.php");
}
?>

Conclusion

Admittedly, it's not the most secure solution. A malicious user could easily find the file called "processScore.php" and add whatever score they like. However, for the simple requirements of the game, it will suffice.

No comments:

Post a Comment