• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
Question by NateChen · Oct 20, 2020 at 11:54 AM · 3dserverdatabaseconnectionphp

How to send data from Unity C# to PHP server?

I've been trying to practice unity these days, and I'd like to send the name of the object whenever I click to PHP server. I use VSCode to write PHP and XAMPP to set up Apache server. I just can't seem to send their name to my PHP. The results are always Undefined index: objectNameKey if I use $_POST["objectNameKey"] or an empty array if I use $_POST. I've been trying some of solutions but to no avail. I'm using unity 2017.4 and 2018.4, PHP 7.4.11.

PHP server

 <?php
     $objectName = $_POST["objectNameKey"];
     print_r($objectName);
     var_dump($objectName);
 ?>

The results were Undefined index: objectNameKey.

I tried

 if(isset($_POST["objectNameKey"])){
     $objectName = $_POST["objectNameKey"];
     print_r($objectName);
     var_dump($objectName);
 }

The results were nothing since I didn't write else to respond to this. I guess the objectNameKey is still undefined index.

Then I tried

 $objectName = $_POST;
 print_r($objectName);
 var_dump($objectName);

The results were empty arrays.

select.cs is to get the name of the object whenever I click and this one is working.

select.cs

 using UnityEngine;
 
 public class select : MonoBehavior
 {
     public static string objectName;
     public static bool objEnabled;
 
     void Start(){
     }
 
     void Update()
     {
         if (Input.GetMouseButtonUp(0))
         {
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;
 
             if (Physics.Raycast(ray, out hit))
             {
                 if (hit.collider != null)
                 {
                     Debug.DrawLine(ray.origin, hit.point);
                     objectName = hit.collider.gameObject.name;
                     connectPHP.objectName = objectName;
                     connectPHP.objectEnabled = true;
 
                 }
             }
         }
     }
 }

I can get the name of the object whenever I click. Now this is where the problem starts to happen.

connectPHP.cs is to send the name of the object (objectName) to my PHP server.

I used WWWForm method and used $_POST["objectNameKey"] to catch it and the result was Undefined index: objectNameKey.

connectPHP.cs

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Networking;
 
 public class connectPHP : MonoBehaviour
 {
     
     public static string connectURL = "http://localhost:8080/practice/connect.php";
     public static string objectName;
     public static bool objectEnabled;
 
     // Start is called before the first frame update
     void Start()
     {
     }
     
     //Unity data to PHP
     IEnumerator Upload()
     {
         WWWForm form = new WWWForm();
         form.AddField("objectNameKey", objectName);
         UnityWebRequest www = UnityWebRequest.Post(connectURL, form);
         yield return www.SendWebRequest();
         if (www.isNetworkError || www.isHttpError)
         {
             Debug.Log(www.error);
         }
         else
         {
             Debug.Log("Form upload complete!");
         }
     }
 
     void Update()
     {
         if(objectEnabled == true)
         {
             StartCoroutine(Upload());
             objectEnabled = false;
         }
     }
 }

Then I chose to use MultipartFormSection method. I didn't know what to put in the field part.

 formData.Add(new MultipartFormDataSection("field1=foo&field2=bar"));

So I chose to find some answers. I stumbled upon this youtube video. I tried to copy it. I used $_POST["objectNameKey"] to catch it and the result was still Undefined index: objectNameKey.

 List<IMultipartFormSection> form = new List<IMultipartFormSection>();
 form.Add(new MultipartFormDataSection("objectNameKey", objectName));
 UnityWebRequest www = UnityWebRequest.Post(connectURL, form);
 yield return www.SendWebRequest();
 
 if (www.isNetworkError || www.isHttpError)
 {
     Debug.Log(www.error);
 }
 else
 {
     Debug.Log("Form upload complete!");
 }

Then I tried to use UnityWebRequest.Put method. I used $_POST to catch it and the result is empty array.

 byte[] myData = System.Text.Encoding.UTF8.GetBytes(objectName);
 UnityWebRequest www = UnityWebRequest.Put(connectURL, myData);
 yield return www.SendWebRequest();
 if(www.isNetworkError || www.isHttpError)
 {
     Debug.Log(www.error);
 }
 else
 {
     Debug.Log("Upload Complete!");
 }

I just couldn't send objectName to PHP server.

Then, I saw this from unity documentation.

Note: Many server backend languages do not properly handle POST requests with Content-Type headers set to encoding others than application/x-www-form-urlencoded or multipart/form-data.

Then I thought maybe this was the source of my failure. So I tried to find how others solve this problem. I didn't really know how exactly they did it. I just tried to copy it and changed the values. I used $_POST to catch these two methods and still got nothing. I guessed I didn't change it right or it's right but the data didn't send to the PHP. Please correct me if I'm wrong.

 public class Object{
     public string ObjectName;
 }
 public class connectPHP : MonoBehavior {
     public static string connectURL = "http://localhost:8080/practice/connect.php";
     public static string objectName;
     public static bool objectEnabled;
 
     // Start is called before the first frame update
     void Start()
     {
     }
     
     //Unity data to PHP
     IEnumerator Upload()
     {
         var user = new Object ();
         user.ObjectName = objectName;
         string json = JsonUtility.ToJson (user);
 
         var req = new UnityWebRequest (connectURL, "POST");
         byte[] jsonToSend = new System.Text.UTF8Encoding ().GetBytes (json);
         req.uploadHandler = (UploadHandler)new UploadHandlerRaw (jsonToSend);
         req.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer ();
         req.SetRequestHeader("Content-Type", "Application/json");
         yield return req.SendWebRequest ();
         if (req.isNetworkError || req.isHttpError) {
             Debug.Log (req.error);
         } else {
             Debug.Log("Success.");
         }
     }
 
     void Update()
     {
         if(objectEnabled == true)
         {
             StartCoroutine(Upload());
             objectEnabled = false;
         }
     }
 }

I think I'm supposed to turn objectName into json format. $_POST didn't get anything.

And I tried

 byte[] data = System.Text.Encoding.UTF8.GetBytes (JObject);
 using (UnityWebRequest www = new UnityWebRequest (connectURL)) {
     www.SetRequestHeader ("Content-Type", "application/json");
     www.method = "POST";
     www.uploadHandler = new UploadHandlerRaw (data);
     www.downloadHandler = new DownloadHandlerBuffer ();
 
     yield return www.SendWebRequest ();
 
     if (www.isNetworkError || www.isHttpError) {
         Debug.Log (www.error);
     } else {
         Debug.Log("Success.");
     }
 }

and they all failed. $_POST didn't get anything.

I've tried to pass the data from mssql through PHP to Unity and it has worked. So I'm not sure if it's a connection issue.

connectPHP.cs

 IEnumerator Download()
     {
         using (UnityWebRequest webRequest = UnityWebRequest.Get(connectURL))
         {
             yield return webRequest.SendWebRequest();
 
             if (webRequest.isNetworkError)
             {
                 Debug.Log("Error: " + webRequest.error);
             }
             else
             {
                 Debug.Log("Received: " + webRequest.downloadHandler.text);
             }
         }
     }

I've also tried to add

 www.chunkedTransfer = false;

and it failed too.

I checked access.log. It showed

 - - [16/Oct/2020:11:09:40 +0800] "POST /practice/connect.php HTTP/1.1" 200 281 "-" "UnityPlayer/2018.4.27f1 (UnityWebRequest/1.0, libcurl/7.52.0-DEV)"

I also used Debug.Log(objectName); to make sure that value was sent from select.cs to connectPHP.cs and got [11:20:15] Object001 UnityEngine.Debug.Log(Object).

I've been stuck for days. I really don't know what's wrong with my code. Hope this is clear enough to explain what I've wanted to do. Any help is appreciated.

UPDATE: Still did not successfully send objectName to my PHP. I'm thinking about not using XAMPP and reinstalling Apache and PHP because I noticed that I installed PHP in my C drive before and installed XAMPP in D drive which also had PHP recently. I did not edit my PATH in environmental variables when I first installed PHP and I could still use PHP right now without it. I'm wondering if that could interfere with my connection between PHP and unity. I'm also wondering about change the version of unity to rule out the possibility that it's the bug of 2018.4. I didn't find anyone else had the same problem with me using 2018.4 though.

Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Update about the future of Unity Answers

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta later in June. Please note, we are aiming to set Unity Answers to read-only mode on the 31st of May in order to prepare for the final data migration.

For more information, please read our full announcement.

Follow this Question

Answers Answers and Comments

262 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Server making assetBundles 1 Answer

How can I display a terminal in three dimensional space? 0 Answers

Unity sql PHP script can log in with wrong password, what's wrong? 0 Answers

How to preload video on second scene when using the 1st scene? 0 Answers

Money from unity to mysql db 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges