Protect the PHP file that connects to mySQL

I have a game that connects to a mysql database through a php file. I was wondering how to protect that file from being accessed from, for example, the browser?

In the file I require user id, gold and item. So I check if the userID exist, if the user has the gold that is has sent to the script, and if the item cost is lower or equal to the gold amount that it was sent. If that things happens, the item is sold to the user and the 100 gold coins are deducted from the user gold.

But, is someone “discovers” the path and the variables name, can do something like mydomain/script.php?userid=4&gold=100&item=239 and if the user 4 exists, it has 100 of gold and the item 239 costs 100 o less… the item wild be sold to that user and 100 of gold will be deducted…

So how do you deal with that? I though of also giving a secret code, for example mydomain/script.php?userid=4&gold=100&item=239&secretcode=kdsSDfsdfSDF and then check in the script.php if that code is correct, its like a pre-shared key, but it seems to easy to hack.

What would you do?

I’m far from a security or PHP expert(scratch that - I’m far from a security or PHP newbie), but I believe that the server side highscores script uses an MD5 hash for exactly this purpose: unifycommunity.com

First. It is very difficult to retrieve your file path from the Unity web application and if someone succeeds, I would suggest using MD5 with salt. Salt makes your code more secured. Here is an example.

 public function createHashedData($data){
    $salt = "SoMeWiErDsTrInGwItHnUmBeRs123455"
    $context = hash_init("md5", HASH_HMAC, $salt);
    hash_update($context, $data);
    return hash_final($context);
}

But in your case all this will not do any good if someone comes across your link he can send the data anyways. The best way to do is create a session whenever a user logs into your game and store it in database and delete the session once the person logs off.

By storing the session you can always check the session with the user and if exists deduct the money and stuff.

Benefit: So if someone come across the link he wont be able to do anything since he does not have session data with him and the link will be of no use to him.

I hope this will help.

Dins