Send data from unity3d game to PHP empty variables - php

I want to send data from my game to the Database on the server. In this case, I develop locally but when I click the spacebar button The Database is created but With empty data. No data is sent from my game.
I have to try to improve my code also try to implement the pre statements.
I am not able to use the unitywebrequest because my version of UNITY3D does not have it my version is 5.0.0f4
When I try to insert the data by hand on fields in the editor and then start the preview, and click the spacebar to send the data, but when I click the database create a row but with empty data, what I fail here, can't find the problem
Also, i have aply the debug.log to see if there is any info send from my app to the script and the data is there but i continue not understand why is my code not work correctly, i also provide the prints of the app and database.
I also edit again to make the password hash changes i just did but i dont know if is correct like this
!https://imgur.com/J5R56Xf
!https://imgur.com/pzd7t4e
!https://imgur.com/x9VRK6P
This is my unity code below.
using UnityEngine;
using System.Collections;
public class DataInserter : MonoBehaviour {
public string inputUserName;
public string inputPassword;
public string inputEmail;
public string regdata;
string CreateUserURL = "localhost/InsertUser.php";
// Use this for initialization
void Start () {
//regdata = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Space)) CreateUser(inputUserName, inputPassword, inputEmail, regdata);
}
public void CreateUser(string username, string password, string email, string regdata){
WWWForm form = new WWWForm();
form.AddField("usernamePost", username);
form.AddField("passwordPost", password);
form.AddField("emailPost", email);
form.AddField("regdataPost", regdata);
WWW www = new WWW(CreateUserURL, form);
}
}
And This is my New PHP code below.
//Variables for the connection
$servername = "localhost";
$server_username = "root";
$server_password = "mysql";
$dbName = "wizard2019";
$saveuser = "INSERT INTO users (username, email, password, regdata)
VALUES ('".$username."','".$email."','".$password."','".$regdata."')";
//Variable from the user
$username = $_POST["usernamePost"];
$email = $_POST["emailPost"];
$password = password_hash($_POST["passwordPost"], PASSWORD_DEFAULT);
$regdata = $_POST["regdataPost"];
//$username = "helder";
//$email = "test email";
//$password = "123456";
//$regdata = "20201123";
//Make Connection
$conn = new mysqli($servername, $server_username, $server_password, $dbName);
//Check Connection
if(!$conn){
die("Connection Failed. ". mysqli_connect_error());
}
$sql = $saveuser;
$result = mysqli_query($conn ,$sql);
if(!$result) echo "there was an error";
else echo "Registration Sucessfull";
?>

First of all WWW class has been obsolete. Look at this docs of unity here.
Also you need to use 'Coroutine' to wait until you get a response from WWW. See the code below:
void Start () {
string url = "http://www.example.com/";
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Debug.Log("Success: " + www.data);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
Check this amazing tutorial of Unity with PHP MySQLi here if you really want to stick with your approach.
I recommend you to use UnityWebRequest to POST or GET data. See this official docs here.
For Example:**
IEnumerator Upload()
{
WWWForm form = new WWWForm();
form.AddField("myField", "myData");
using (UnityWebRequest www = UnityWebRequest.Post("http://www.my-server.com/myform", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}

Related

Why UnityWebRequest send empty fields?

I'm facing a frustrating problem right now and I can't see any reason why this doesn't work since is pure Unity developer copy paste code.
I can't send data from Unity to website. Every Unity sent parameter is taken as empty.
That's how my [Web.cs] looks like:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
public class Web : MonoBehaviour
{
public IEnumerator Login(string Username, string Password)
{
Debug.Log(Username);
Debug.Log(Password);
WWWForm Form = new WWWForm();
Form.AddField("loginUser", Username);
Form.AddField("loginPass", Password);
UnityWebRequest www = UnityWebRequest.Post("http://localhost/Login.php", Form);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
Debug.Log(www.error);
else
{
Debug.Log("Form upload complete!");
Debug.Log(www.downloadHandler.text);
}
}
}
And I'm calling it via Login.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Login : MonoBehaviour
{
public InputField UserName;
public InputField Password;
public Button myButton;
private void Start()
{
myButton.onClick.AddListener(() =>
{
StartCoroutine(Main.Instance.Web.Login(UserName.text, Password.text));
});
}
}
The php code looks like:
<?php
$UserName = $_GET["loginUser"];
$Password = $_GET["loginPass"];
$myfile = fopen("testfile.txt", "a");
fwrite($myfile, "Username: $UserName\nPassowrd: $Password\n\n");
?>
So, when I manually acces the path link, I get the expected results:
http://localhost/Login.php?loginUser=Test&loginPass=Ok
https://i.imgur.com/s0bP5tJ.png
But when I do it with Unity, XAMPP writes the parameters as empty.
A debug photo:
https://i.imgur.com/r1IUTy2.png
It appears you're sending a POST request to a GET request.
Try this: UnityWebRequest.Get(...)
#Kale, thank you, I kinda still don't understand what's the difference between post and get methods :-?
For future searchers, that's how I managed to resolve the issue:
public class Web : MonoBehaviour
{
public IEnumerator Login(string Username, string Password)
{
WWWForm Form = new WWWForm();
string Link = "http://localhost/Login.php?loginUser=" + Username + "&loginPass=" + Password;
UnityWebRequest www = UnityWebRequest.Get(Link);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
Debug.Log(www.error);
else
{
Debug.Log("Form upload complete!");
Debug.Log(www.downloadHandler.text);
}
}
}

What is Causing my Code to Not Return Any Data When Trying to Send a Login Request to a Local Server?

For about a month, I have been trying to figure out why my code will not return anything after posting a wwwForm (I have also tried the newer equivalent of this function but I had no luck with that either.) The nameField and passwordField are taken from text boxes within the game and the code used in my login script is copied and pasted from a Register script but I have changed the file location to the login.php file. The register script works fine and I can add new users to my database but the login script only outputs "Form Sent." and not the "present" that should return when the form is returned and it never gets any further than that point meaning that it lets the user through with no consequence if they use an invalid name because the script never returns an answer. What should I do to fix this?
Thanks,
Unity Code:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class Login : MonoBehaviour
{
public InputField nameField;
public InputField passwordField;
public Button acceptSubmissionButton;
public void CallLogInCoroutine()
{
StartCoroutine(LogIn());
}
IEnumerator LogIn()
{
WWWForm form = new WWWForm();
form.AddField("username", nameField.text);
form.AddField("password", passwordField.text);
WWW www = new WWW("http://localhost/sqlconnect/login.php", form);
Debug.Log("Form Sent.");
yield return www;
Debug.Log("Present");
if (www.text[0] == '0')
{
Debug.Log("Present2");
DatabaseManager.username = nameField.text;
DatabaseManager.score = int.Parse(www.text.Split('\t')[1]);
Debug.Log("Log In Success.");
}
else
{
Debug.Log("User Login Failed. Error #" + www.text);
}
}
public void Validation()
{
acceptSubmissionButton.interactable = nameField.text.Length >= 7 && passwordField.text.Length >= 8;
}
}
login.php:
<?php
echo "Test String2";
$con = mysqli_connect('localhost', 'root', 'root', 'computer science coursework');
// check for successful connection.
if (mysqli_connect_errno())
{
echo "1: Connection failed"; // Error code #1 - connection failed.
exit();
}
$username = mysqli_escape_string($con, $_POST["username"]);
$usernameClean = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$password = $_POST["password"];
if($username != $usernameClean)
{
echo "7: Illegal Username, Potential SQL Injection Query. Access Denied.";
exit();
}
// check for if the name already exists.
$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE username='" . $usernameClean . "';";
$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query failed"); // Error code # 2 - name check query failed.
if (mysqli_num_rows($namecheck) != 1)
{
echo "5: No User With Your Log In Details Were Found Or More Than One User With Your Log In Details Were Found"; // Error code #5 - other than 1 user found with login details
exit();
}
// get login info from query
$existinginfo = mysqli_fetch_assoc($namecheck);
$salt = $existinginfo["salt"];
$hash = $existinginfo["hash"];
$loginhash = crypt($password, $salt);
if ($hash != $loginhash)
{
echo "6: Incorrect Password"; // error code #6 - password does not hash to match table
exit;
}
echo "Test String2";
echo"0\t" . $existinginfo["score"];
?>
This problem was solved by changing the IENumerator LogIn() to IENumerator Start(). The program ran correctly when it was started at the beginning of a scene but not when it was triggered by a button being pressed. Weirdly, the Register() function in another script (which shares a lot of its code with this one) ran fine when triggered from a button. I'm not sure why this is.
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class Login : MonoBehaviour
{
public InputField nameField;
public InputField passwordField;
public Button acceptSubmissionButton;
IEnumerator Start()
{
WWWForm form = new WWWForm();
form.AddField("username", nameField.text);
form.AddField("password", passwordField.text);
WWW www = new WWW("http://localhost/sqlconnect/login.php", form);
Debug.Log("Form Sent.");
yield return www;
Debug.Log("Present");
if (www.text[0] == '0')
{
Debug.Log("Present2");
DatabaseManager.username = nameField.text;
DatabaseManager.score = int.Parse(www.text.Split('\t')[1]);
Debug.Log("Log In Success.");
}
else
{
Debug.Log("User Login Failed. Error #" + www.text);
}
}
public void Validation()
{
acceptSubmissionButton.interactable = nameField.text.Length >= 7 && passwordField.text.Length >= 8;
}
}

Login script issue with database

I wrote a login script for a website that I am building using resources I have found online. When I ran my code on a local server it worked fine but now that I am actually running it online on a real server it doesn't work. I think I have narrowed down my error but with being new to PHP and not having prior experience with MySql I can't really fix my problem. This is the file for the login script:
//login file
<?php
class Login{
private $db_connection = null;
public function __construct(){
session_start();
$this->dologinWithPostData();
}
private function dologinWithPostData(){
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$this->db_connection()->connect_errno) {
// escape the POST stuff
$email = $_POST['email'];
// database query, getting all the info of the selected user (allows login via email address in the
// username field)
$sql = "SELECT email, password
FROM users
WHERE email = '" . $email ."'";
$result_of_login_check = $this->db_connection->query($sql);//This is 0
// if this user exists
if ($result_of_login_check->num_rows == 1) {
// get result row (as an object)
$result_row = $result_of_login_check->fetch_object();
// using PHP 5.5's password_verify() function to check if the provided password fits
// the hash of that user's password
if ($_POST['password'] == $result_row->password) {
// write user data into PHP SESSION (a file on your server)
$_SESSION['email'] = $result_row->email;
$_SESSION['user_login_status'] = 1;
} else {
$this->errors[] = "Wrong password. Try again.";
$_SESSION['user_login_status'] = 0;
}
} else {
$this->errors[] = "This user does not exist.";
}
} else {
$this->errors[] = "Database connection problem.";
}
}
print_r($this->errors);
}
public function isUserLoggedIn()
{
if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) {
return true;
}
// default return
return false;
}
}
?>
I run it in another file that is essentially the following:
//Run file
require_once("dbconfig.php");
include_once("login.php");
$login = new Login();
if($login->isUserLoggedIn() == true){
//go to another page }
The variables used to access the database are instantiated in dbconfig.php and are correct. With this code I get an error that says the page is not working and is unable to handle the request. When I comment out the line
if (!$this->db_connection()->connect_errno) {
and the else statement following it, the output is "This user does not exist". So I think the error has something to do with $this->db_connection()->connect_errno). If you can find where I went wrong or have any advice on how to rewrite the script to make it better, it is greatly appreciated.
This is a database establishing error your live remote server database configuration is different.Please verify you dbconfig.php file make sure
database name, host , port , username , password are well defined with your live database
This is wrong:
if (!$this->db_connection()->connect_errno) {
db_connection is simply a variable containing your DB connection object. It is NOT a method.
You probably want
if (!$this->db_connection->connect_errno) {
^--note lack of ()
instead.
I think issue with this follwoing check. your result gets more than 1 records.
// if this user exists
if ($result_of_login_check->num_rows == 1) {
......
}else{
$this->errors[] = "This user does not exist.";
}
make sure your email address is unique in Data table, if it is not unique then your above statement will fail and show the text "This user does not exist." from else part

PHP user log in, database authentication and redirect help needed

I'm a beginner developer stuck in a tough situation needing to deliver this project I haven't been able to grasp completely.
There is a page with a login button. When you press that button, it takes you to wp admin instead of verifying your given permission level in wp mysql database, and based on that transferring you to the appropriate web site. I figured out how to connect to database and verify user but I'm not sure how put in multiple parameters because there are 5 sections of privileges given to users. Based on their privileges they get sent to another part of the website. I'm using the header php function to redirect but I am unsure if I can include it in the same file and how do I tie this file to existing wp login page? Please help!
<?php
error_reporting(0);
session_start();
class logmein {
var $hostname_logon = 'localhost';
var $database_logon = '';
var $username_logon = '';
var $password_logon = '';
var $user_table = 'logon';
var $user_column = 'useremail';
var $pass_column = 'password';
var $user_level = 'userlevel';
var $encrypt = false;
function dbconnect(){
$connections = mysql_connect($this->hostname_logon, $this->username_logon, $this->password_logon) or die ('Unabale to connect to the database');
mysql_select_db($this->database_logon) or die ('Unable to select database!');
return;
}
function login($table, $username, $password){
$this->dbconnect();
if($this->user_table == ""){
$this->user_table = $table;
}
if($this->encrypt == true){
$password = md5($password);
}
header("Location: https://example.com/members/index.php");
For your quick setup here us example multi-user-role-based-login-in-php-with-mysql
This site have mention everything about your needs. Use "roleid" column in user table so that you identify that user type is what.

Posting form data from VB.NET to PHP script

So I am trying to make a login form on my vb.net application that would connect in my mysql database via my php script. So I've set up a wampp server to test it out. Got my php code below
<?php
if($_POST)
{
if(isset($_POST["username"]) && isset($_POST["password"]))
{
$connect = mysql_pconnect("localhost","root","");
if($connect)
{
$select = mysql_select_db("ktmf",$connect);
if($select)
{
$user = mysql_escape_string($_POST["username"]);
$pwd = mysql_escape_string($_POST["password"]);
$GetRows = mysql_query("SELECT * FROM users WHERE username='$user' AND password='$pwd'");
$RowCount=mysql_num_rows($GetRows);
if($RowCount>0)
{
die("Correct !");
}
else
{
die("Incorrect !");
}
}
else
{
die("Unable to select database." . mysql_error());
}
}
else
{
die("Unable connect to database." . mysql_error());
}
}
else
{
die("Access Denied!");
}
}
else
{
die("Access Denied!");
}
?>
and then I got my vb.net code there
Imports System.Net
Imports System.Text
Public Class login
Function AuthUser(ByVal AuthenticationPage As String, ByVal Username As String, ByVal Password As String) As Boolean
Dim wc As New WebClient()
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
Dim Data As String = String.Format("username={0}&password={1}", WebUtility.UrlEncode(Username), WebUtility.UrlEncode(Password))
Dim ResponseBytes() As Byte = wc.UploadData(AuthenticationPage, "POST", Encoding.ASCII.GetBytes(Data))
Dim Response As String = Encoding.ASCII.GetString(ResponseBytes)
If Response.Contains("Correct") Then
Return True
Else
Return False
End If
End Function
Private Sub login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If AuthUser("http://127.0.0.1/login.php", TextBox1.Text, TextBox2.Text) Then
Me.Hide()
works.Show()
Else
MsgBox("You have provided invalid username or password. Unable to login.")
End If
End Sub
End Class
So when I try to login with the Application I got the Error "You have provided invalid username or password. Unable to login." wich I specified incase of error.
I still dont know what I did wrong, But if someone could help me I'd apreciate.
thanks
Your question does not contain much information, so only generaly:
1) Check what actual response (if any) you get
2) If you do not get any response, check web server log to see, if the request make it there at all
3) Test your PHP script independently on VB.NET. E.g. Simple HTML form would do.
If you share with us your findings based on above, you may get more specific answers.

Categories