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
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
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