Github – mirceak/apiserver-unity-laravel-passport: a well detailed tutorial for a server based project made in unity. this template provides you with every step you need to take to setup your own php server using laravel and having it communicate with unity.

Apiserver-unity-laravel-passport

A well detailed tutorial for a server based project made in Unity. This template provides you with every step you need to take to setup
your own php server using laravel and having it communicate with unity.

This tutorial is designed for someone with basic computer knowledge that has never seen the technologies we are going to be using so
bear with me until we get to the interesting stuff.

First let’s install what we need.

  1. Unity 3D
  2. Xampp
  3. Git
  4. Npm
  5. Composer

How can i access a php file on a server via unity for mysql- database manipulation?

As you indicated in the comments, You are using PHP version 7.2.19, and used code that is a bit older. That code uses mysql_ functions, which were deprecated in PHP version 5.5.0 and removed in PHP 7.

I tried to change that code, it worked on my pc ( PHP 7.3, MySQL ) so it should work on your server too.

Please recreate your table ( if possible ) with this code as for some reason tutorial you sent doesn’t use Auto Increment and also there is very small place for data to insert ( varchar(20) for password ? )

I have also added mysqli_real_escape_string which is to prevent SQL injection.
I have added sha256 to your passwords as you don’t want to save them plain-text.

SQL Table creation:

CREATE TABLE `users` (
    id bigint auto_increment primary key,
    email varchar(256) not null,
    pwd   varchar(256) not null,
    constraint users_so_email_uindex
    unique (email)
);

And PHP Code

<?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 = "your_server";
$username = "username";
$password = "password";
$dbname = "database_name";


//Connect to your database
$db = mysqli_connect($hostname, $username, $password, $dbname) OR DIE ("Unable to connect to database! Please try again later.");

function login($db){
    // Escape string and prevent possible SQL injection
    $email = $_POST['email'];
    $pwd = $_POST['pwd'];

    // Prepare SQL statement
    $statement = $db->prepare("SELECT * FROM `users` WHERE `email`=?);
    $statement->bind_param("s", $email);
    $statement->execute();
    $row = mysqli_fetch_assoc($result);

    if($result->num_rows > 0){
       $hashed_pwd = $row['pwd'];
     }

    if(password_verify($pwd, $hashed_pwd)){
        echo 'User verified successfully!';
    }

    // Close SQL Statement
    $statement->close();

    echo '{"success":false,"msg":"Email and/or Password Invalid"}';
}

function register($db){

    // Escape string and prevent possible SQL injection
    $email = $_POST['email'];
    $pwd =  password_hash($_POST['pwd'], PASSWORD_DEFAULT);

    // Prepare SQL statement for check existing user
    $statement = $db->prepare("SELECT * FROM `users` WHERE `email`=?");
    $statement->bind_param("s", $email);
    $statement->execute();

    // Get result
    $results = $statement->get_result();

    // User already exists
    if($results && $results->num_rows > 0) {
        echo '{"success":false,"msg":"Users Exists"}';
        $statement->close();
        return;
    }

    // Close statement for check existing user
    $statement->close();

    // Prepare SQL statement for insertion
    $statement = $db->prepare("INSERT INTO `users` (email, pwd) VALUES (?, ?)");
    $statement->bind_param("ss", $email, $pwd);

    // Execute insert statement
    if($statement->execute()) {
        echo '{"success":true,"msg":"User registered successfully"}';

        $statement->close();
        return;
    }

    // Something went wrong and user was not registered
    echo '{"success":false,"msg":"Unable to register user"}';
}

function forgot($db){
    echo '{"success":false,"msg":"Feature not yet implemented"}';
}

$action = null;

if (isset($_GET['action'])) {
    $action = $_GET['action'];
}

if ($action == "login") {
    login($db);
} elseif ($action == "register") {
    register($db);
} elseif ($action == "forgot") {
    forgot($db);
}

$db->close();

exit();

**EDIT: ** As suggested in the comments, I have edited the code to go with SQL Statements – Thanks Immorality

var url = authphpurl   "?action=login";

List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("email="   emailText.text   "&pwd="   passwordText.text));

UnityWebRequest www = UnityWebRequest.Post(url, formData);
yield return www.SendWebRequest();

Same snippet can be used for REGISTER

EDIT : PHP works, now UNITY. I did not work in unity once, but as I was looking for solution ( Form data not sending to PHP ), I saw this solution. It may help. Source: https://docs.unity3d.com/Manual//UnityWebRequest-SendingForm.html

Let’s setup laravel.

You are now hosting your very own website! But this is not what we want so we need to move on because there is alot of fun ahead of us!

Okay now we have all the dependencies we need. Let’s get on to setting things up inside Laravel. At this point you should be using some
sort of IDE like Sublime Text or PhpStorm or Visual Studio Code or whatever you feel like.

Using the IDE of your choice follow these steps:

  • Open the .env file in the root folder of the project.
  • Replace the “DB_*” fields as follows:
  • Open the composer.json file in the root folder of the project.
  • In the “require-dev”: {} object add the following line:
  • In the GitBash terminal paste in this code ( composer update --dev )
  • Open the AppServiceProvider.php file in /app/Providers/.
  • Replace the register function as follows:
  • In the GitBash terminal paste this code ( php artisan migrate ). If you get an “Specified key was too long” error do the
    following three steps, if not skip them.
  • Add the following line after the “namespace AppProviders;” line:
  • Replace the boot function as follows:

Unity3d авторизация в wordpress (woocommerce)

Делаю авторизацию в приложении Unity для своего поднятого сайта (магазина) на WordPress(woocommerce).

При вводе логина и пароля, приложение должно возвращать мне из БД id пользователя и его name. С логином все отлично совпадение есть, а вот c паролем проблема: совпадение не происходит.

В Unity приложении я к примеру ввожу пароль “1234qwerty”, при помощи связи unity с php-скриптом он кодируется
в вид MD5 и отправляется в базу для сравнение его в ячейке, в ячейке БД пароль лежит примерно в таком виде: “$P$BBoBeLvbVYRyFLR5OcuqvPrmKEIKU2/”.

В итоге решил проверить в каком виде пароль доходит до базы для сравнения, и он доходит в таком виде “06a8647723d4d285aefdb02ed285220b” который естественно не совпадает с паролем который лежит в ячейке БД:”$P$BBoBeLvbVYRyFLR5OcuqvPrmKEIKU2/”.

И как добиться такой кодировки пароля что бы они совпадали без понятия так как в php мало опыта, без совпадения не могу сделать нормальную авторизацию с вводом логина и пароля.

Связь с БД сайта делаю при помощи php скрипта:

<?
$command=$_POST['command'];
$databasehost="*******";
$databaseuser="*******";
$databasepassword="*******";
$databasename="*******";
$db = mysql_connect($databasehost,$databaseuser,$databasepassword)or die("cannot connect"); 
mysql_select_db($databasename,$db)or die("cannot select DB");
mysql_query('SET CHARACTER SET utf8');
mysql_query('SET NAMES utf8');
switch($command)
{
case "logined":
$login=$_POST['login']; //from Unity strings
$pass=$_POST['pass'];   //from Unity strings
//$pass = sha1($pass);
$pass = md5($pass); //кодировка в md5

$res = mysql_query("SELECT * FROM wp_users WHERE user_login='$login'"); //AND user_pass='$pass'");  
$res_myrow = mysql_fetch_array($res);
$dbPass = $res_myrow['user_pass'];                                                                  
$id = $res_myrow['ID'];   //! empty                                                                         
$name = $res_myrow['user_nicename'];                                                                

if(password_verify($pass, $dbPass))
{
echo "done ";
}else{
echo "Error password_verify ";
} 
echo "us->$login : pas->$pass : id->$id : name->$name";
break;
}
?>

В Unity вот такой скрипт для отправки полей: login и pass

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MysqlConnect : MonoBehaviour {

private string username = ""; //Переменная для хранения имени
private string pswd = ""; //Переменная для хранения пароля
public string url = "*******"; //Переменная для хранения адреса

//Создание метода, отвечающего за подключение и передачу данных
public void Connect(){
    WWWForm form = new WWWForm();
    form.AddField("command", "logined");
    form.AddField("login", username);
    form.AddField("pass", pswd);
    WWW www = new WWW(url, form);
    StartCoroutine(WaitReqwest(www));
}

private IEnumerator WaitReqwest(WWW www){
    yield return www;
    if (www.text.Length > 0)
    {
        Debug.Log("Ответ "   www.text);
    }
}

//Создаём метод OnGUI()
void OnGUI()
{
    //Создаём текстовое поле для ввода имени пользователя
    username = GUI.TextField(new Rect(Screen.width/2-100, Screen.height/2-100, 200, 20), username, 20);

    //Создаём текстовое поле для ввода пароля
    pswd = GUI.TextField(new Rect(Screen.width/2-100, Screen.height/2-75, 200, 20), pswd, 12);

    //Создаём кнопку для произведения подключения
    if (GUI.Button(new Rect(Screen.width/2-100, Screen.height/2-25, 200, 20), "Connect"))
    {
        Connect();
    }
  }
}

Как организовать безопасную работу mysql php для игры на unity?

Если злоумушленник, декомпилировав игру получит прямые ссылки к скриптам PHP, может ли он в теории чего нибудь натворить плохого?

Эти скрипты PHP должны быть выполнимыми не должны быть скачиваемыми (обычно дефолтно настроенный веб-сервер так и делает). То есть при запрос скрипта, веб-сервер не отдаст его как текстовый файл, а выполнит все инструкции пхп и потом вернёт только то, что пхп выведет. Например, всё, что заключено в будет скрыто, кроме того, что выводится функциями echo, print и подобными.

Вы не скинули файл register.php целиком, но подозреваю, что он весь внутри <?php тега, поэтому можно не переживать, что обратившийся к скрипту пользователь увидит параметры коннекта к базе.

По безопасности в целом — есть два подхода:
1) Сделать обычную регистрацию и авторизацию внутри Юнити приложения. Как я понимаю, у вас сейчас так и сделано. После регистрации Юнити получает токен и использует его для всех последующих запросов. Токен желательно делать протухающим со временем.
2) Сделать регистрацию и авторизацию на сайте, пройдя которую человек может получить доступ к странице, в которую встроено Юнити приложение. И при рендеринге приложения ему сразу же передаётся такой же токен для запросов, что и в пункте выше.

Вопрос лишь в том, хотите вы давать доступ в приложение только зареганным у вас на сайте людям или хотите распространять приложение самостоятельно, а сайт будет невидимым бэкендом для него.

Похожее:  Сдек curl запросы? — Хабр Q&A

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *