如何通过 Unity 访问服务器上的 PHP 文件以进行 MySQL 数据库操作?

我目前正在为在线 Unity 游戏开发登录系统。我的目标是在我的服务器上建立一个数据库并检查用户是否已注册。如果您需要比提供的更多背景信息,我会遵循本教程。


我的服务器上有一个 PHP 脚本和一个数据库。PHP 脚本位于我的网络服务器 (purplepandagames.com/httpdocs/auth.php) 的默认文件夹下。


$hostname = "<localhost:3306>";

$username = "<username>";

$dbname = "<dbName>";

$password = "<password>";


mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");

mysql_select_db($dbname);


为了连接到服务器,我在 PHP 脚本中使用了这些值。本地主机是否正确?或者主机名是 Purplepandagames.com?该数据库附属于 Purplepandagams.com。


在 Unity 中,我有一个名为 AuthManager 的脚本,用于处理连接。以下是 C# 脚本的一些可能错误的部分:


string authphpurl = "https://purplepandagames.com/auth.php";    //enter the complete URL for auth.php


    IEnumerator 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"];

        }

     }

对于 simpleJSON,我正在使用这个。


如果我像这样运行代码,HTTP/1.1 500 Internal Server Error则会出现错误消息。如果我将 authphpurl 更改为仅https://purplepandagames.com,则没有反馈并且该 Debug.Log("Response:" + www.downloadHandler.text);语句仅输出 index.html 文件。


该网站具有 SSL 认证,这可能是一个问题。


总的来说,像这样解决这个问题是个好主意吗?我会在上传到数据库之前加密密码。但目前我不明白是什么阻止了其他人也能够操纵这个数据库。


临摹微笑
浏览 320回答 1
1回答

qq_花开花谢_0

正如您在评论中指出的,您使用的是 PHP 版本 7.2.19,并且使用的代码有点旧。该代码使用 mysql_ 函数,这些函数在 PHP 5.5.0 版中已弃用,并在 PHP 7 中删除。我试图更改该代码,它可以在我的电脑(PHP 7.3,MySQL)上运行,因此它也可以在您的服务器上运行。请使用此代码重新创建您的表(如果可能),因为出于某种原因,您发送的教程不使用自动增量,而且插入数据的位置非常小(varchar(20)作为密码?)我还添加了 mysqli_real_escape_string 以防止 SQL 注入。我已将 sha256 添加到您的密码中,因为您不想将它们保存为纯文本。SQL表创建:CREATE TABLE `users` (&nbsp; &nbsp; id bigint auto_increment primary key,&nbsp; &nbsp; email varchar(256) not null,&nbsp; &nbsp; pwd&nbsp; &nbsp;varchar(256) not null,&nbsp; &nbsp; constraint users_so_email_uindex&nbsp; &nbsp; unique (email));和 PHP 代码<?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){&nbsp; &nbsp; // Escape string and prevent possible SQL injection&nbsp; &nbsp; $email = $_POST['email'];&nbsp; &nbsp; $pwd = $_POST['pwd'];&nbsp; &nbsp; // Prepare SQL statement&nbsp; &nbsp; $statement = $db->prepare("SELECT * FROM `users` WHERE `email`=?);&nbsp; &nbsp; $statement->bind_param("s", $email);&nbsp; &nbsp; $statement->execute();&nbsp; &nbsp; $row = mysqli_fetch_assoc($result);&nbsp; &nbsp; if($result->num_rows > 0){&nbsp; &nbsp; &nbsp; &nbsp;$hashed_pwd = $row['pwd'];&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; if(password_verify($pwd, $hashed_pwd)){&nbsp; &nbsp; &nbsp; &nbsp; echo 'User verified successfully!';&nbsp; &nbsp; }&nbsp; &nbsp; // Close SQL Statement&nbsp; &nbsp; $statement->close();&nbsp; &nbsp; echo '{"success":false,"msg":"Email and/or Password Invalid"}';}function register($db){&nbsp; &nbsp; // Escape string and prevent possible SQL injection&nbsp; &nbsp; $email = $_POST['email'];&nbsp; &nbsp; $pwd =&nbsp; password_hash($_POST['pwd'], PASSWORD_DEFAULT);&nbsp; &nbsp; // Prepare SQL statement for check existing user&nbsp; &nbsp; $statement = $db->prepare("SELECT * FROM `users` WHERE `email`=?");&nbsp; &nbsp; $statement->bind_param("s", $email);&nbsp; &nbsp; $statement->execute();&nbsp; &nbsp; // Get result&nbsp; &nbsp; $results = $statement->get_result();&nbsp; &nbsp; // User already exists&nbsp; &nbsp; if($results && $results->num_rows > 0) {&nbsp; &nbsp; &nbsp; &nbsp; echo '{"success":false,"msg":"Users Exists"}';&nbsp; &nbsp; &nbsp; &nbsp; $statement->close();&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; // Close statement for check existing user&nbsp; &nbsp; $statement->close();&nbsp; &nbsp; // Prepare SQL statement for insertion&nbsp; &nbsp; $statement = $db->prepare("INSERT INTO `users` (email, pwd) VALUES (?, ?)");&nbsp; &nbsp; $statement->bind_param("ss", $email, $pwd);&nbsp; &nbsp; // Execute insert statement&nbsp; &nbsp; if($statement->execute()) {&nbsp; &nbsp; &nbsp; &nbsp; echo '{"success":true,"msg":"User registered successfully"}';&nbsp; &nbsp; &nbsp; &nbsp; $statement->close();&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; // Something went wrong and user was not registered&nbsp; &nbsp; echo '{"success":false,"msg":"Unable to register user"}';}function forgot($db){&nbsp; &nbsp; echo '{"success":false,"msg":"Feature not yet implemented"}';}$action = null;if (isset($_GET['action'])) {&nbsp; &nbsp; $action = $_GET['action'];}if ($action == "login") {&nbsp; &nbsp; login($db);} elseif ($action == "register") {&nbsp; &nbsp; register($db);} elseif ($action == "forgot") {&nbsp; &nbsp; forgot($db);}$db->close();exit();**编辑:** 正如评论中所建议的,我已经编辑了代码以使用 SQL 语句 - 谢谢不道德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();相同的片段可用于 REGISTER编辑: PHP 工作,现在统一。我曾经没有统一工作过,但是当我正在寻找解决方案(表单数据不发送到 PHP)时,我看到了这个解决方案。它可能会有所帮助。来源:https : //docs.unity3d.com/Manual//UnityWebRequest-SendingForm.html
打开App,查看更多内容
随时随地看视频慕课网APP