Tutorial: Unity and PHP login script - simple but useful

EDIT2: AGAIN, this is not secured in any way. Learn and study how to make security programming / communication if you want this. This is just a tutorial about connecting PHP + Unity, READ THE WHOLE TOPIC!!!

Hello everyone,

I learned a lot from this forum and with some users, so this tutorial I made is for helping that ones who needs to use PHP with Unity (using Javascript this time) and dont know how. I want to thank Tempest (http://forum.unity3d.com/viewtopic.php?t=18846) because his tutorial and scripts made me learn the firsts steps into this.

This tutorial is really simple, for those who want to use C#, I suggest to enter in the topic of Tempest (URL above), his script if more advanced than mine and its harder than mine to learn, even that is simple anyway.
So, as you discovered, Iā€™m using Javascript for this one.
I will not teach how to program in PHP, so try other tutorial yourself if you have doubts with PHP.

=== Create the database called: SCORES

CREATE TABLE `scores` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 30 ) NOT NULL ,
`password` VARCHAR( 50 ) NOT NULL
) ENGINE = innodb;

Iā€™m using 3 fields in this table: ID, NAME and PASSWORD. Change for whatever you want in the future.

Insert at least this data to your name TABLE (FOR TESTS PURPOSE):

INSERT INTO `scores` ( `id` , `name` , `password` )
VALUES (
NULL , 'xandeck', MD5( '1234' )
);

=== Create the PHP file called: check_scores.php

<?
// CONNECTIONS =========================================================
$host = "localhost"; //put your host here
$user = "myuser"; //in general is root
$password = "mypassword"; //use your password here
$dbname = "mydatabase"; //your database
mysql_connect($host, $user, $password) or die("Cant connect into database");
mysql_select_db($dbname)or die("Cant connect into database");
// =============================================================================
// PROTECT AGAINST SQL INJECTION and CONVERT PASSWORD INTO MD5 formats
function anti_injection_login_senha($sql, $formUse = true)
{
$sql = preg_replace("/(from|select|insert|delete|where|drop table|show tables|,|'|#|\*|--|\\\\)/i","",$sql);
$sql = trim($sql);
$sql = strip_tags($sql);
if(!$formUse || !get_magic_quotes_gpc())
  $sql = addslashes($sql);
  $sql = md5(trim($sql));
return $sql;
}
// THIS ONE IS JUST FOR THE NICKNAME PROTECTION AGAINST SQL INJECTION
function anti_injection_login($sql, $formUse = true)
{
$sql = preg_replace("/(from|select|insert|delete|where|drop table|show tables|,|'|#|\*|--|\\\\)/i","",$sql);
$sql = trim($sql);
$sql = strip_tags($sql);
if(!$formUse || !get_magic_quotes_gpc())
  $sql = addslashes($sql);
return $sql;
}
// =============================================================================
$unityHash = anti_injection_login($_POST["myform_hash"]);
$phpHash = "hashcode"; // same code in here as in your Unity game

$nick = anti_injection_login($_POST["myform_nick"]); //I use that function to protect against SQL injection
$pass = anti_injection_login_senha($_POST["myform_pass"]);
/*
you can also use this:
$nick = $_POST["myform_nick"];
$pass = $_POST["myform_pass"];
*/
if(!$nick || !$pass) {
    echo "Login or password cant be empty.";
} else {
    if ($unityHash != $phpHash){
        echo "HASH code is diferent from your game, you infidel.";
    } else {
        $SQL = "SELECT * FROM scores WHERE name = '" . $nick . "'";
        $result_id = @mysql_query($SQL) or die("DATABASE ERROR!");
        $total = mysql_num_rows($result_id);
        if($total) {
            $datas = @mysql_fetch_array($result_id);
            if(!strcmp($pass, $datas["password"])) {
                echo "LOGADO - PASSWORD CORRECT";
            } else {
                echo "Nick or password is wrong.";
            }
        } else {
            echo "Data invalid - cant find name.";
        }
    }
}
// Close mySQL Connection
mysql_close();
?>

Now save it with that name I said above. Put in the same directory of your webpage host.

Now lets create the Unity game. Make a new project (or use one you already have, whatever). Create a new Javascript file and change the name for whatever you want, here I will use phpUnity.
Put this code on:

private var formNick = ""; //this is the field where the player will put the name to login
private var formPassword = ""; //this is his password
var formText = ""; //this field is where the messages sent by PHP script will be in

var URL = "http://mywebsite/check_scores.php"; //change for your URL
var hash = "hashcode"; //change your secret code, and remember to change into the PHP file too

private var textrect = Rect (10, 150, 500, 500); //just make a GUI object rectangle

function OnGUI() {
	GUI.Label( Rect (10, 10, 80, 20), "Your nick:" ); //text with your nick
	GUI.Label( Rect (10, 30, 80, 20), "Your pass:" );

	formNick = GUI.TextField ( Rect (90, 10, 100, 20), formNick ); //here you will insert the new value to variable formNick
	formPassword = GUI.TextField ( Rect (90, 30, 100, 20), formPassword ); //same as above, but for password

	if ( GUI.Button ( Rect (10, 60, 100, 20) , "Try login" ) ){ //just a button
		Login();
	}
	GUI.TextArea( textrect, formText );
}

function Login() {
	var form = new WWWForm(); //here you create a new form connection
	form.AddField( "myform_hash", hash ); //add your hash code to the field myform_hash, check that this variable name is the same as in PHP file
	form.AddField( "myform_nick", formNick );
	form.AddField( "myform_pass", formPassword );
	var w = WWW(URL, form); //here we create a var called 'w' and we sync with our URL and the form
	yield w; //we wait for the form to check the PHP file, so our game dont just hang
	if (w.error != null) {
		print(w.error); //if there is an error, tell us
	} else {
		print("Test ok");
		formText = w.data; //here we return the data our PHP told us
		w.Dispose(); //clear our form in game
	}

	formNick = ""; //just clean our variables
	formPassword = "";
}

Put this code inside a game object, or even your Main camera. Just HIT play and it must work :slight_smile:
Now, use your imagination and make your game insert data into your database, or return more data, etc.

HAVE FUN. Put your doubts here and I will be glad to help, when I have some time, hehe.

EDIT: Oh, I forgot, use the name ā€˜xandeckā€™ and password ā€˜1234ā€™ to test. Put diferent values to see the results :wink:

EDIT3: How to better handling security, SQL injection and etc, tip by MasaMuneWos
Link: http://forum.unity3d.com/threads/24721-Tutorial-Unity-and-PHP-login-script-simple-but-useful/page8?p=1588877&viewfull=1#post1588877

3 Likes

ie what i did a while back but now am using smartfox to do it

Man Down login system

NIce, I forgot about this :wink:

except mine isnā€™t ā€œsimpleā€ it has stuff like the rss feed sorta and more so.

Iā€™m having trouble getting this to work on my 50webs account. Itā€™s shared hosting, so Iā€™m guessing Iā€™m not supposed to be using ā€œlocalhostā€ but something different.

I will try contacting their support staff. Out of curiosity, which web host did you use for your project, xandeck? I chose 50webs because it seemed cheaper than any dedicated hosting offers I could find, but every time a tutorial doesnā€™t seem to work for me, I question my decisionā€¦

Asking 50webs will give you the answer, but it should be available from wherever you can set up a mysql database.

For example,

Siteground.com sets up the mysql databases locally for each hosting package, so the address is ā€˜localhostā€™.

1and1.com sets up all mysql databases on seperate servers, which have their own address ā€˜serverNumber.1and1.comā€™.

It depends on your host.

I just noticed this in an FAQ:

Would this prevent your technique from working? At the moment the php file is on their web server, but the Unity game is on my hard drive. (But surfing to the PHP page maually gives the same error.)

Youā€™re not remotely connecting to the mysql database. Youā€™re connecting to a php page, which is connected locally.

If the application was running on your computer and connected directly (no php scripts) to the mysql database, then that would be a remote connection.

What exact errors are you getting?

Yeah, my words follow Tempest :smile:

I use a webhost service from my country (Brazil), but any MySQL server configured in the server must work. Genereally is localhost.

You need to create the unity web game file and then save it in the same host your mysql is.

not true :slight_smile:

since this uses a php page it can be in a standalone if you use php pages or some sort of page on a server.

it can also be in any unity thing if you use php without any modifications.

I know this bloodtiger10, :slight_smile:

But for a web browse game he needsā€¦ thats what I meanā€¦ :wink:

Sorry if I said with a wrong wordā€¦ my english is improving :sweat_smile:

your part about having to upload it to the same server as the database is completely false. not the webplayer part.

There are some security issues with this approach though (unless sending it over https and then there are still some).

First of all the users password is sent to the webserver in cleartext. It isnt untill the webserver checks against the database that the password is transformed to a md5.
Beacuse of this anyone packet sniffing on the network would get the users password as clear text and could imidiately login afterwards.

Thatā€™s could be changed easy with a MD5 implementation, for example the one here: http://www.unifycommunity.com/wiki/index.php?title=MD5

As I said in the post, its a very basic way to make it work PHP and WWW with Unityā€¦ Iā€™m not covering security. But yes, for sure it needs to be implemented.

:wink:

Ive been holding onto this tutorial for awhile now, but now that im using it i just wanted to sayā€¦

Thank you Xandeck

This cleared up alot of questions i had about talking to a server, and gave me a good head start.

No problem :wink:

Actually, Iā€™m not using PHP anymore, we have to change the project because it will take a big scaleā€¦ Iā€™m using SmartFox with Unity now, so my login process connects MySQL database with SFS, with no PHP.

C ya :wink:

Nice start for me! Thanks a lot indeed ;D Iā€™m arguing some security issues in my mind, If some one can sniff the line then he would sniff the hash too. So whatā€™s the security point of ā€œmyform_hashā€ ?

Thats just to see if the codes are the sameā€¦ not really security you knowā€¦ :lol:

It would be nice if we could make a string of all inputs, then MD5 it in Unity then send the hash and the data, there in PHP we make the same string from received inputs and MD5 it, then compare the received MD5 with the one we made in PHP, if both are the sameā€¦ if notā€¦ So, is there a way to use SHA1 or MD5 in Unity? :roll:

Besides I would be grateful if you can please post the same tutorial in SmartFox :sweat_smile: