Email Authentication in Unity with PHP and Mysql as Backend

Search for a command to run...

No comments yet. Be the first to comment.
Learn the Building Blocks of Basic User Interface in Unity app and Game development.

Get started with Magic Leap 2 development without a device.

As a developer sometime you will require to create windows icon file with extension ".ico". Normally you will get a png image with which you need to create the ico file. You can easily convert any png file to an ico file using GIMP. GIMP is a free so...
In this article, I would be sharing how you can show native menu bar in your flutter windows app. This is something which is still not provided by default by flutter. This article is starting point for adding the menu system in your windows app. You ...
C is one of the fastest language around. Many a times you might need to use it in your development activities to speed up some processes. For one of my requirement I need to interact with MYSQL in C. Although there are many different articles which e...
Authentication is one of the basic need for any mobile app. Email and Mobile Numbers are the most commonly used parameters for authentication. In this tutorial you will be discovering how to do Email Authentication in Unity with PHP and Mysql as Backend.
So this tutorial is ideally suited for some one who is looking to add authentication to a unity based app. Here are some of the stuff which you learn:
Here are the prerequisites for Email Authentication in Unity with PHP and Mysql.
You can get the source file with the complete project files for free. Go ahead and click the below button to get the files. [activecampaign form=89]
To get started with the tutorial you will need to first create a Unity project and then save the default scene.
Here are the steps to create a project in Unity.
The scene will be saved in the "Assets/Scenes" folder
There are several components which needs to be added to create the Email Authentication user interface. You will be discovering them one by one below.
Canvas is the base on which all the UI components will be added. Here are the steps to add a canvas.
The main panel will act as the top most panel which will occupy whole screen.
A Panel will be added to the Scene. Now here are some more steps to be done in the inspector.
Here are the steps to add the input field for Email.
An Input field will be added. Now you will need to change some of the properties in the Inspector.
Here are the steps to add the input field for Password.
An Input field will be added. Now you will need to change some of the properties in the Inspector.
Before you add the Login and Register buttons, you will need to add another panel which will contain these buttons. Here are the steps to add the container panel.
The panel will be added. Here are the list of changes to be done in the inspector.
Here are the steps to add a Login button.
Now a Button has been added. You will need to work on the inspector tab.
Here are the steps to add a Login button.
Now a Button has been added. You will need to work on the inspector tab.
Just for debugging purpose you will need to add a Text box to show the response messages from the backend server. Here are the steps to do that.
An Input field will be added. Now you will need to change some of the properties in the Inspector.
As this tutorial on Email Authentication in Unity with PHP and Mysql, it is required that you have your php hosting with Mysql ready.
You will need to add a table to the database. It will hold the email and password of the users. Here is the SQL query to create the table.
\-- --------------------------------------------------------
--
-- Table structure for table \`users\`
--
CREATE TABLE \`users\` (
\`id\` bigint(10) NOT NULL,
\`email\` varchar(100) NOT NULL,
\`pwd\` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Create a php file "auth.php" on your php hosting server. Change the database details in the php file before uploading. Here is the php script
<?php
//These variable values need to be changed by you before deploying
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "<dbhosturl>";
$username = "<username>";
$dbname = "<dbname>";
$password = "<dbpassword>";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
function login(){
}
function register(){
}
function forgot(){
}
$action = $_GET\['action'\];
if($action == "login"){
//Fetching from your database table.
$query = "SELECT \* FROM users where email = '".$_POST\['email'\]."' AND pwd = '".$_POST\['pwd'\]."'";
$result = mysql_query($query);
$valid = false;
if ($result) {
while($row = mysql_fetch_array($result)) {
$valid=true;
}
}
if($valid){
echo '{"success":true,"msg":"User Verified Successfully"}';
}
else{
echo '{"success":false,"msg":"Email and/or Password Invalid"}';
}
exit();
}
else if($action == "register"){
//Fetching from your database table.
$query = "SELECT \* FROM users where email = '".$_POST\['email'\]."'";
$result = mysql_query($query);
$user_exists = false;
if ($result) {
while($row = mysql_fetch_array($result)) {
$user_exists = true;
}
}
if($user_exists){
echo '{"success":false,"msg":"Users Exists"}';
}
else{
$query = "INSERT INTO users (email,pwd) VALUES ('".$_POST\['email'\]."', '".$_POST\['pwd'\]."')";
if(mysql_query($query)){
echo '{"success":true,"msg":"User registered successfully"}';
}
else{
echo '{"success":false,"msg":"Unable to register user"}';
}
}
exit();
}
else if($action == "forgot"){
//$email = $_POST\['email'\];
echo '{"success":false,"msg":"Feature not yet implemented"}';
}
else{
exit();
}
In this tutorial you will be using SimpleJson for parsing the json response from the php server.
Here are the step to add the script.
Double Click and open "SimpleJson.cs" file in MonoDevelop for editing. Once the file is open in MonoDevelop, replace the code with the code of SimpleJson.cs at the following location.
http://wiki.unity3d.com/index.php/SimpleJSON
Now that the UI and Backend is ready, it is time to write the scripts for authentication.
Here are the step to add the script.
Double Click and open "AuthManager.cs" file in MonoDevelop for editing.
Once the file is open in MonoDevelop, replace the code with the below code. Make sure you change the value of "authphpurl" as per your hosting details.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using SimpleJSON;
public class AuthManager : MonoBehaviour {
public Text emailText;
public Text passwordText;
public Text responseText;
string authphpurl = "http://yourserver.com/php/auth.php";//enter the complete url for auth.php
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void handleLoginButtonClick(){
StartCoroutine(PostDataForLogin ());
}
public void handleRegisterButtonClick(){
StartCoroutine(PostDataForRegister ());
}
IEnumerator PostDataForLogin(){
Debug.Log("PostDataForLogin!");
WWWForm form = new WWWForm();
form.AddField("email", emailText.text);
form.AddField("pwd", passwordText.text);
var url = authphpurl+"?action=login";
UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();
Debug.Log ("Response:"+www.downloadHandler.text);
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
responseText.text = www.error;
}
else {
Debug.Log("Form upload complete!");
JSONNode jsonNode = SimpleJSON.JSON.Parse(www.downloadHandler.text);
Debug.Log("success : "+jsonNode\["success"\]);
Debug.Log("message : "+jsonNode\["msg"\]);
responseText.text = jsonNode \["msg"\];
}
}
IEnumerator PostDataForRegister(){
Debug.Log("PostDataForRegister!");
WWWForm form = new WWWForm();
form.AddField("email", emailText.text);
form.AddField("pwd", passwordText.text);
var url = authphpurl+"?action=register";
UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();
Debug.Log ("Response:"+www.downloadHandler.text);
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
responseText.text = www.error;
}
else {
Debug.Log("Form upload complete!");
JSONNode jsonNode = SimpleJSON.JSON.Parse(www.downloadHandler.text);
Debug.Log("success : "+jsonNode\["success"\]);
Debug.Log("message : "+jsonNode\["msg"\]);
responseText.text = jsonNode \["msg"\];
}
}
}
Now that the UI and the scripts are ready, you can start integrating them.
You will need to add an empty game object to hold the AuthManager script. Here are the steps the do that.
Now the AuthManager script ready to be used.
Here are the steps to set the outlets.
Now all the three outlets are set.
Here are the steps to add the event handler.
The OnClick event handler is now ready for Login button.
Here are the steps to add the event handler.
The OnClick event handler is now ready for Login button.
Now you can go ahead and run the app by clicking on the play button on top. You should be able to register a user. After that use the same credentials to login.
Now that you have got your Email Authentication ready, you can start adding more scenes to this project. Gradually this project can take shape of a professional app. You can download the complete source code at the starting of this tutorial.
If you have any query or if the tutorial has helped you in any way, just add a comment below.