Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Tutorial: Unity and PHP login script - simple but useful

Discussion in 'Multiplayer' started by xandeck, Jun 10, 2009.

  1. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    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

    Code (csharp):
    1.  
    2. CREATE TABLE `scores` (
    3. `id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    4. `name` VARCHAR( 30 ) NOT NULL ,
    5. `password` VARCHAR( 50 ) NOT NULL
    6. ) ENGINE = innodb;
    7.  
    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):

    Code (csharp):
    1.  
    2. INSERT INTO `scores` ( `id` , `name` , `password` )
    3. VALUES (
    4. NULL , 'xandeck', MD5( '1234' )
    5. );
    6.  
    === Create the PHP file called: check_scores.php

    Code (csharp):
    1.  
    2. <?
    3. // CONNECTIONS =========================================================
    4. $host = "localhost"; //put your host here
    5. $user = "myuser"; //in general is root
    6. $password = "mypassword"; //use your password here
    7. $dbname = "mydatabase"; //your database
    8. mysql_connect($host, $user, $password) or die("Cant connect into database");
    9. mysql_select_db($dbname)or die("Cant connect into database");
    10. // =============================================================================
    11. // PROTECT AGAINST SQL INJECTION and CONVERT PASSWORD INTO MD5 formats
    12. function anti_injection_login_senha($sql, $formUse = true)
    13. {
    14. $sql = preg_replace("/(from|select|insert|delete|where|drop table|show tables|,|'|#|\*|--|\\\\)/i","",$sql);
    15. $sql = trim($sql);
    16. $sql = strip_tags($sql);
    17. if(!$formUse || !get_magic_quotes_gpc())
    18.   $sql = addslashes($sql);
    19.   $sql = md5(trim($sql));
    20. return $sql;
    21. }
    22. // THIS ONE IS JUST FOR THE NICKNAME PROTECTION AGAINST SQL INJECTION
    23. function anti_injection_login($sql, $formUse = true)
    24. {
    25. $sql = preg_replace("/(from|select|insert|delete|where|drop table|show tables|,|'|#|\*|--|\\\\)/i","",$sql);
    26. $sql = trim($sql);
    27. $sql = strip_tags($sql);
    28. if(!$formUse || !get_magic_quotes_gpc())
    29.   $sql = addslashes($sql);
    30. return $sql;
    31. }
    32. // =============================================================================
    33. $unityHash = anti_injection_login($_POST["myform_hash"]);
    34. $phpHash = "hashcode"; // same code in here as in your Unity game
    35.  
    36. $nick = anti_injection_login($_POST["myform_nick"]); //I use that function to protect against SQL injection
    37. $pass = anti_injection_login_senha($_POST["myform_pass"]);
    38. /*
    39. you can also use this:
    40. $nick = $_POST["myform_nick"];
    41. $pass = $_POST["myform_pass"];
    42. */
    43. if(!$nick || !$pass) {
    44.     echo "Login or password cant be empty.";
    45. } else {
    46.     if ($unityHash != $phpHash){
    47.         echo "HASH code is diferent from your game, you infidel.";
    48.     } else {
    49.         $SQL = "SELECT * FROM scores WHERE name = '" . $nick . "'";
    50.         $result_id = @mysql_query($SQL) or die("DATABASE ERROR!");
    51.         $total = mysql_num_rows($result_id);
    52.         if($total) {
    53.             $datas = @mysql_fetch_array($result_id);
    54.             if(!strcmp($pass, $datas["password"])) {
    55.                 echo "LOGADO - PASSWORD CORRECT";
    56.             } else {
    57.                 echo "Nick or password is wrong.";
    58.             }
    59.         } else {
    60.             echo "Data invalid - cant find name.";
    61.         }
    62.     }
    63. }
    64. // Close mySQL Connection
    65. mysql_close();
    66. ?>
    67.  
    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:

    Code (csharp):
    1.  
    2. private var formNick = ""; //this is the field where the player will put the name to login
    3. private var formPassword = ""; //this is his password
    4. var formText = ""; //this field is where the messages sent by PHP script will be in
    5.  
    6. var URL = "http://mywebsite/check_scores.php"; //change for your URL
    7. var hash = "hashcode"; //change your secret code, and remember to change into the PHP file too
    8.  
    9. private var textrect = Rect (10, 150, 500, 500); //just make a GUI object rectangle
    10.  
    11. function OnGUI() {
    12.     GUI.Label( Rect (10, 10, 80, 20), "Your nick:" ); //text with your nick
    13.     GUI.Label( Rect (10, 30, 80, 20), "Your pass:" );
    14.  
    15.     formNick = GUI.TextField ( Rect (90, 10, 100, 20), formNick ); //here you will insert the new value to variable formNick
    16.     formPassword = GUI.TextField ( Rect (90, 30, 100, 20), formPassword ); //same as above, but for password
    17.  
    18.     if ( GUI.Button ( Rect (10, 60, 100, 20) , "Try login" ) ){ //just a button
    19.         Login();
    20.     }
    21.     GUI.TextArea( textrect, formText );
    22. }
    23.  
    24. function Login() {
    25.     var form = new WWWForm(); //here you create a new form connection
    26.     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
    27.     form.AddField( "myform_nick", formNick );
    28.     form.AddField( "myform_pass", formPassword );
    29.     var w = WWW(URL, form); //here we create a var called 'w' and we sync with our URL and the form
    30.     yield w; //we wait for the form to check the PHP file, so our game dont just hang
    31.     if (w.error != null) {
    32.         print(w.error); //if there is an error, tell us
    33.     } else {
    34.         print("Test ok");
    35.         formText = w.data; //here we return the data our PHP told us
    36.         w.Dispose(); //clear our form in game
    37.     }
    38.  
    39.     formNick = ""; //just clean our variables
    40.     formPassword = "";
    41. }
    42.  
    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 :wink:

    EDIT3: How to better handling security, SQL injection and etc, tip by MasaMuneWos
    Link: http://forum.unity3d.com/threads/24...useful/page8?p=1588877&viewfull=1#post1588877
     
    Last edited: May 18, 2014
    RoyalCoder, sinsnow and SCOFIELD92 like this.
  2. bloodtiger10

    bloodtiger10

    Joined:
    Nov 9, 2008
    Posts:
    619
  3. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    NIce, I forgot about this :wink:
     
  4. bloodtiger10

    bloodtiger10

    Joined:
    Nov 9, 2008
    Posts:
    619
    except mine isn't "simple" it has stuff like the rss feed sorta and more so.
     
  5. WarpZone

    WarpZone

    Joined:
    Oct 29, 2007
    Posts:
    326
    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...
     
  6. Tempest

    Tempest

    Joined:
    Dec 10, 2008
    Posts:
    1,286
    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.
     
  7. WarpZone

    WarpZone

    Joined:
    Oct 29, 2007
    Posts:
    326
    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.)
     
  8. Tempest

    Tempest

    Joined:
    Dec 10, 2008
    Posts:
    1,286
    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?
     
  9. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    Yeah, my words follow Tempest :D

    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.
     
  10. bloodtiger10

    bloodtiger10

    Joined:
    Nov 9, 2008
    Posts:
    619
    not true :)

    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.
     
  11. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    I know this bloodtiger10, :)

    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 :oops:
     
  12. bloodtiger10

    bloodtiger10

    Joined:
    Nov 9, 2008
    Posts:
    619
    your part about having to upload it to the same server as the database is completely false. not the webplayer part.
     
  13. perlohmann

    perlohmann

    Joined:
    Feb 12, 2009
    Posts:
    221
    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.
     
  14. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    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:
     
  15. CynderR

    CynderR

    Joined:
    Jul 27, 2009
    Posts:
    2
    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.
     
  16. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    No problem ;)

    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:
     
  17. Allen0012

    Allen0012

    Joined:
    Sep 5, 2009
    Posts:
    93
    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" ?
     
  18. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    Thats just to see if the codes are the same... not really security you know... :D
     
  19. Allen0012

    Allen0012

    Joined:
    Sep 5, 2009
    Posts:
    93
    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:
     
  20. Allen0012

    Allen0012

    Joined:
    Sep 5, 2009
    Posts:
    93
    Besides I would be grateful if you can please post the same tutorial in SmartFox :oops:
     
  21. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    MD5 we can, yes, but I only know a way with C#.
    SHA1... maybe, I dont know.

    I'm still learning how to use it good and I'm a little bit busy testing and making the code for the game :D , but when I finish, I can make something yes... did you already checked the tutorials from Thomas Lund? They are really good and the docs of SFS and SFS+Unity API is good too. :wink:
     
  22. Allen0012

    Allen0012

    Joined:
    Sep 5, 2009
    Posts:
    93
    Well thanks then ;) I'm gonna check that out...
     
  23. perlohmann

    perlohmann

    Joined:
    Feb 12, 2009
    Posts:
    221
    you can use SHA1 and alot of other sha's from the C# System.Security.Cryptography too.
     
  24. Allen0012

    Allen0012

    Joined:
    Sep 5, 2009
    Posts:
    93
    Seems working in C#. But a lot to do before getting to the same SHA1() funtion in php. C# encryption functions use byte[] as input.

    ;) Thanks
     
  25. radiolobito

    radiolobito

    Joined:
    Jun 12, 2009
    Posts:
    117
    first: Thanks for this simple and fantastic tutorial

    second: How can I take the web-sided message (i know that's in the variable "formText") to Unity can execute actions?

    The web says (in example):
    "Good", but in reality is
    "Good
    "

    i tried to compare with "Good"+"/n", but is not working.

    Somebody can tellme hay can i link the 'echo' of PHP to a function of JavaScript?

    Thanks again
     
  26. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    Is this a typo in the post, or did you use forward slash by mistake instead of backslash for the \n escape?
     
  27. radiolobito

    radiolobito

    Joined:
    Jun 12, 2009
    Posts:
    117
    sorry about the mistake, its "\n"
     
    rollandgrogg likes this.
  28. radiolobito

    radiolobito

    Joined:
    Jun 12, 2009
    Posts:
    117
    nobody have the answer? please give me a clue
     
  29. Tempest

    Tempest

    Joined:
    Dec 10, 2008
    Posts:
    1,286
    Please post the PHP snippet where you're echoing the field. Make sure isn't anything else being added to the web page after you echo that value (even something like a blank space after the ?> at the end of the PHP snippet.
     
  30. trinitysj

    trinitysj

    Joined:
    Jan 15, 2010
    Posts:
    54
    do you have an example of how you connect smartfox with a mysql database. i am doing a multiplayer game and need to utilize a database as well for player names login info, stats, that sort of thing.

    thanks.
     
  31. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    There is a very good example in the SFS docs, as I can remember. I'm not using anymore, the project I was on was not approved... but I will keep learning this year, I hope. I'm in another project now.

    The Docs are pretty easy and useful... take a time to read and you will be good :wink:
     
  32. trinitysj

    trinitysj

    Joined:
    Jan 15, 2010
    Posts:
    54
    I tried your sample at the beginning of this thread and it worked great. I just wanted to know if there was a total php solution to doing multiplayer or is SFS is the better option. i see that SFS has a DB engine built into it and might give that a shot.

    I have looked at the multiplayer island demo project and have done quite a bit with it.

    again just curious.
     
  33. zhuangfengzi

    zhuangfengzi

    Joined:
    Feb 7, 2010
    Posts:
    11
    If I want to run "Application LoadLevel(1)",I should
    how to write code in login.js.


    waiting.......

    At first,thank you!
     
  34. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    Sorry, dont know what you mean...
     
  35. zhuangfengzi

    zhuangfengzi

    Joined:
    Feb 7, 2010
    Posts:
    11
    var check =false;

    if( check==true ){

    Application.LoadLevel(1)

    }

    //with php echo

    if(formText ==" "){

    check=true;

    }

    I write the code,but no work.

    Shoud i how to write the code???


    Thank you!

    Waiting......
     
  36. crasyboy42

    crasyboy42

    Joined:
    Jun 29, 2010
    Posts:
    28
    i have 2 problems
    1 he says always nickname or password is wrong :S
    2 how can i add multiply accounts??

    btw nice work :D the only 1 i found that work(without errors)
     
  37. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    Hey man, thanks... it will be nice if someone upgrade this a little bit :D
    I made lots of improvement in this, but cant post it yet, need to translate some vars, etc...

    Ok, about the first error, check your database tables if they are right, because the code is pretty much what it says.
    What do you mean in the second question? Do you want the same person have multiple accounts?

    Post your code here and I see what I can do. Anyway, it is better if you are familiar with PHP and Database stuff, otherwise it will be hard to explain :wink:
     
  38. crasyboy42

    crasyboy42

    Joined:
    Jun 29, 2010
    Posts:
    28
  39. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    Do you want to create an account inside Unity? Well, you will have to make the scripts inside (name, password, etc) and then you can send the data to a php script file. Thats one way and I think its the easier one.

    Sorry, but for this you need to know how to script in PHP, I cannot make such a script right now... trying learn a little bit PHP and then post you doubts here :wink:
     
  40. crasyboy42

    crasyboy42

    Joined:
    Jun 29, 2010
    Posts:
    28
    i have create 1 on my site and that 1 dont see the database -.- i think the sql database hate me
    but canyou help me with the problem that it dont reconise my input in unity??
     
  41. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    Post here your scripts and them tell me what you doing so I can check what is going on :D
     
  42. crasyboy42

    crasyboy42

    Joined:
    Jun 29, 2010
    Posts:
    28
    it is a mysql error but i dont know what i dit wrong :(

    i have done it 2 times i have my sql database on 000webhost.com is that the problem?
     
  43. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    I can only help you if I see the scripts now... how can I help you if I did not see where to begin from? What is the MySQL error?
     
  44. crasyboy42

    crasyboy42

    Joined:
    Jun 29, 2010
    Posts:
    28
    Nick or password is wrong.
    he says that with every entry :(
     

    Attached Files:

  45. crasyboy42

    crasyboy42

    Joined:
    Jun 29, 2010
    Posts:
    28
    i found the problem the database have the passwords witout md5 ;)
    but now another question
    how can i put lvl and exp in a gui in unity? the lvl and exp are on the database :)
     
  46. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    Just read the data the same way you get the nickname :wink:

    Make it read after the login
     
  47. crasyboy42

    crasyboy42

    Joined:
    Jun 29, 2010
    Posts:
    28
    that part i just dont understand ;)
     
  48. kardang

    kardang

    Joined:
    Jun 29, 2010
    Posts:
    3
    The script above does not always work. Contents that is created by echo or print does not appear in the www.data using my webserver and provider.

    Solve this by using flush(); after all prints or echo that completes the evaluation.

    <?php

    print "This will show up for sure";
    flush(); // because of me.

    ?>
     
  49. xandeck

    xandeck

    Joined:
    Apr 2, 2009
    Posts:
    563
    I dont know why this not worked for you... made many tests here in the past (I'm still using similar code) and I had no problems at all.

    Anyway, I'm happy that a possible problem now have a possible solution ;)
     
  50. kardang

    kardang

    Joined:
    Jun 29, 2010
    Posts:
    3
    Yes, it is the strangest thing.

    Now, most of my print or echo lines show up, but still there are some that dont. Seems a bit like those that have concatednated with variable names are simply ignored. Second day now of debugging, thought I had it nailed, but, not completely.

    It is one of the strangest problems I have seen.

    Code (csharp):
    1. print "This should show third";
    2. print "fourth";
    This both gets transferred to Unity.

    But if i Do this :
    Code (csharp):
    1. print "This should show third";
    2.  
    3. print "RECEIVING NICK AND PASS"   $_GET["myform_nick"]  " "  $_GET["myform_pass"];
    4.  
    5. print "fourth";
    Then the second AND third line disappears. Seems like it is waiting for something to happen, and it does not.

    Also, just realised. The browser shows stuff that IS NOT in the html source, and some of that stuff is also transferred to unity. (I changed from POST to GET to be able to debug using browser window. But here it is even stranger, not in the source, but on screen? Im getting the jeepers creppers)