C# to PHP - WWW Update?

Hello everyone!

I’m struggling! I’m trying to make a log in system and hook it up to a server, just a bit of practice more than anything. I think I have most of it worked out but for some reason the field just won’t fill in. It’s been a couple of days that I have been racking my brain trying to find an answer, but alas, I’m at a loss.

Any help in understanding the WWW to UnityWebRequest updates will be much appreciated as I’m pretty sure that is where the issue is going wrong with my coroutines.

The two scripts for signing up so far are:
(C# in Unity):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class Login : MonoBehaviour
{
    #region Variables

    //Static Variables
    public static string Email = "";
    public static string Password = "";

    //Public Variables
    public string CurrentMenu = "Login";

    //Private Variables
    private string CreateAccountURL = "http://127.0.0.1/CreateAccountT.php";
    private string LoginURL = "";
    private static string suEmail = "";
    private static string suUsername = "";
    private static string suPassword = "";
    private static string Passconf = "";

    //GUI Test Section
    public float X;
    public float Y;
    public float Width;
    public float Height;

#endregion

    // Start is called before the first frame update
    void Start()
    {
       
    } // End of Start Function

    // Main GUI function:
    void OnGUI() {
        // If the current menu is the login, then display the login menu...
        //...by calling the login gui function.
        if(CurrentMenu == "Login")
        {
            // Calling on the Login GUI:
            LoginGUI();
        }
    }// End OnGUI

#region Custom methods
    // This method will login the accounts.
    void LoginGUI() {
        //Create account button and login button
        if (GUI.Button(new Rect(598, 427, 151, 26), "create account"))
        {
            if (Passconf == suPassword)
            {
                StartCoroutine("CreateAccount");
            }

            else
            {
                Debug.Log ("Do passwords match?");
            }
        }
        if (GUI.Button(new Rect(351, 325, 151, 26), "log in"))
        {

        }// End Buttons
       
        // Creating the log in text boxes...
        Email = GUI.TextField(new Rect(345, 231, 171, 18), Email);
        Password = GUI.TextField(new Rect(345, 282, 171, 18), Password);
        // ... and the sign up text boxes
        suEmail = GUI.TextField(new Rect(588, 231, 171, 18), suEmail);
        suUsername = GUI.TextField(new Rect(588, 282, 171, 18), suUsername);
        suPassword = GUI.TextField(new Rect(588, 328, 171, 18), suPassword);
        Passconf = GUI.TextField(new Rect(588, 378, 171, 18), Passconf);
        // Create random int field for bot protection

    } // End Login GUI


    #endregion

    #region Coroutines
    //Actually create the account
    IEnumerator CreateAccount()
    {
        // This is what sends messages to our PHP Scripts
        WWWForm Form = new WWWForm();
        // These fields are variables we are sending to the server
        Form.AddField("Email", suEmail);
        Form.AddField("Password", suPassword);
        Form.AddField("Username", suUsername);
        WWW CreateAccountWWW = new WWW(CreateAccountURL, Form);
        //Wait for PHP to send something back to the game
        yield return CreateAccountWWW;
        //Error: Cannot Connect to Account Creation
        if (CreateAccountWWW.error != null)
        {
            Debug.LogError("Cannot Connect to Account Creation");
        }
        //Acount Created Successfully
        else
        {

            string CreateAccountReturn = CreateAccountWWW.text;
            if (CreateAccountReturn == "Success")
            {
                Debug.Log("Success");
            }

        }// End Account Creation Successfully

    }// End create account



    #endregion
}

It doesn’t throw up any of the error logs I have put in, so I’m sure it is the coroutines and the outdated WWW, but maybe someone will see something I have missed.

I’ve tried changing the link, and when I do it lets me know it can’t connect, which means I think I have nailed the issue down to being specifically saving the information to the data base.

As for the PHP script, it could be completely wrong, I am just starting out with PHP, anyone that knows better may well laugh at it, but as it is important for finding out what exactly the issue is:

<?php
    //Email, Password and Username
       $Email = $_REQUEST["Email"];
    $Password = $_REQUEST["Password"];
    $Username =  $_REQUEST["Username"];
   
    //PHP only
    $Hostname = "localhost";
    $DBName = "gameaccounts";
    $User = "root";
    $PasswordP = "";
   
    $conn = new mysqli($Hostname, $User, $PasswordP, $DBName);
   
    if($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
        }
   
   
    if(!$Email || !$Password|| !$Username) {
        echo "Empty";
    } else {
        $SQL = "SELECT * FROM  accounts WHERE Email ='" . $Email . "'";
        $result = @mysqli_query($SQL) or die ("DB Error");
        $Total = mysqli_num_rows($Result);
        if($Total == 0) {
            $insert = "INSERT INTO `accounts` (`Email`, `Password`, `Username`) values ('" . $Email . "', MD5('" . $Password . "', MD5 ('" . $Username . "')))";
            $SQL1 = mysqli_query($insert);
            echo "Success";
        } else {
            echo "AlreadyUsed";
        }

    }

    //close mysql
    mysqli_close($conn);
   
?>

Networking, UnityWebRequest, WWW, Postman, curl, WebAPI, etc:

2 Likes

Well, first and foremost you should watch this video about SQL injections. After you’ve done that, go to your PHP file, press CTRL+A and hit delete -.-. Next look up how to use prepared statements in PHP and start over. Even though this sounds funny, it really isn’t. Even it’s not as life-threatening like forgetting to tell a member of a primitive tribe to not stick metal things into wall outlets, it’s about in the same ballpark.

Since we already talk about security, keep in mind that http sends your user name and password unencrypted. So if you ever plan to open this webserver to the internet, keep in mind that http is kinda obsolete and you should use https.

Apart from all this, what is the exact behaviour you’re observing? Have you checked the database if anything has actually changed? Currently you only check the returned data if it’s “Success”. Have you tried actually printing out what is returned by your PHP script? Depending on the error settings of the php config, php may throw an exception which would actually be returned as text. So just logging the return text is always the first thing you should do.

Note that depending on your php config, certain super globals could be disabled. If you run this server on your own, you should check your PHP config. If the server is hosted externally you usually do not have access to the config. In this case you may want to check the output of phpinfo() how the config looks like.

In production you generally do not want to have php output any kinds or errors back to the user. However during development, especially when debugging, you may want to add those 3 lines at the top of your PHP file:

    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

It will output any errors or warnings which you can read as plaintext in the response on the Unity side. As I said earlier, make sure you actually inspect the returned text.

AFAIK the WWW class still works fine, however I haven’t tried it in the latest Untiy versions. While the WWW class is a bit easier to use, it has several limitations and minor flaws. So in the end, sooner or later you want to switch to the UnityWebRequest.

1 Like