Search Unity

Need help with scripting .php for uploading .txt files to http server

Discussion in 'Multiplayer' started by MrSaoish, Apr 13, 2017.

  1. MrSaoish

    MrSaoish

    Joined:
    Oct 1, 2016
    Posts:
    22
    Hello everyone, I think this question is more or less related to php, but I don't where else I could ask it. So here I am.

    I am trying to upload my userdata as json from unity web request to my local http server store as .txt file. I think it's pretty straight forward to do it on the Unity side, but I am having trouble to script a .php to handle this request correctly which result all the data in the .txt is missing but "{}".

    Here is a C# script running on my unity side:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5.  
    6. public class Uploader : MonoBehaviour {
    7.  
    8.     // Use this for initialization
    9.     void Start () {
    10.         StartCoroutine(UploadMethoid_3("SomeUserName"));
    11.     }
    12.  
    13.     IEnumerator UploadMethod_1(string username) {//***Attempt 1: 414 Request-URI Too Long
    14.         string data = JsonUtility.ToJson(DataBase.GetUserdata(username));
    15.         string post_url = "http://127.0.0.1/upload.php" + "?name=" + WWW.EscapeURL(username) + "&data=" + data;
    16.         WWW post = new WWW(post_url);
    17.         yield return post;
    18.         if (post.error != null)
    19.             Debug.Log(post.error);
    20.     }
    21.  
    22.     IEnumerator UploadMethod_2(string username) {//***Attempt 2: Successfully uploaded, but I don't know how am I suppse to script the upload.php to handle PUT        
    23.         string data = JsonUtility.ToJson(DataBase.GetUserdata(username));
    24.         UnityWebRequest www = UnityWebRequest.Put("http://127.0.0.1/upload.php" + "?name=" + WWW.EscapeURL(username), WWW.EscapeURL(data));
    25.         www.SetRequestHeader("Content-Type", "application/json");
    26.         yield return www.Send();
    27.         if (www.isError) {
    28.             Debug.Log(www.error);
    29.         } else {
    30.             Debug.Log("Uploaded");
    31.         }
    32.     }
    33.  
    34.     IEnumerator UploadMethoid_3(string username) {//***Attempt 3: Successfully uploaded, but the new .txt file contains only "{}" rather than userdata                                              
    35.         string data = JsonUtility.ToJson(DataBase.GetUserdata(username));
    36.         var bytes = System.Text.Encoding.UTF8.GetBytes(JsonUtility.ToJson(data));
    37.         var form = new WWWForm();
    38.         form.AddBinaryData("file", bytes, username + ".txt", "text/json");
    39.         var w = new WWW("http://127.0.0.1/upload.php", form);
    40.         yield return w;
    41.         if (w.error != null)
    42.             Debug.Log(w.error);
    43.         else
    44.             Debug.Log("Uploaded.");
    45.     }
    46. }
    I am using xampp to run a local http server, and putting my upload.php and all user's .txt files under xampp/htdocs folder. And here is the upload.php:
    Code (php):
    1. <?php                
    2.        if (($_FILES["file"]["type"] == "text/json")){
    3.            if ($_FILES["file"]["error"] > 0){
    4.              echo "Return Code: " . $_FILES["file"]["error"] . "";
    5.            }
    6.            else{                  
    7.              echo "Upload: " . $_FILES["file"]["name"] . "";
    8.              echo "Type: " . $_FILES["file"]["type"] . "";
    9.              echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb";
    10.              echo "Temp file: " . $_FILES["file"]["tmp_name"] . "";
    11.                move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
    12.            }
    13.     }
    14.     else{
    15.         echo "Invalid file";
    16.     }
    17. ?>
    UploadMethoid_3 from Uploader.cs is the closest one I can get so far and, and once I click play on unity side, the console print "Uploaded" which means it has no problem on uploading those json data. But when I check on my .txt file on in my xampp/htdocs, it only has "{}" rather than my player data. I have checked the php error log and it shows the upload.php runs without any error. I think the problem is happening in my upload.php but I don't know what it is since I just start learning php like today, could anyone please help me out here?
     
    Last edited: Apr 14, 2017
  2. donnysobonny

    donnysobonny

    Joined:
    Jan 24, 2013
    Posts:
    220
    So, it looks like your third method (UploadMethoid_3) from the client-side is spot on. You are telling the server that the content being sent is text/json, and then sending the json text as the payload. That's exactly what you want to do from the client-side.

    On your server side however (the php), you are expecting the data as part of a file, which is not what the client is doing. You will find the content being sent from the client-side in your "input stream". In php, you can read the content of the input stream like so:

    Code (PHP):
    1. $content = file_get_contents("php://input");
    It's worth noting that you can only read the input stream once, not that this should be an issue for you, but yeah as soon as you call the above function once, the input stream is flushed (emptied).

    So then, simply json_decode the $content variable and you have your data on the server-side.

    Hopefully this helps. Let me know if you are still stuck.
     
    Last edited: Apr 13, 2017
    MrSaoish likes this.
  3. MrSaoish

    MrSaoish

    Joined:
    Oct 1, 2016
    Posts:
    22
    Thank you very much for the your help. It turns out one of developer on my project used to script php, and he helped me to script the upload.php with POST method. Here is the source in case someone run into similar problem and need something to start with:

    Code (CSharp):
    1.     IEnumerator UpLoadUserData(string username) {        
    2.         string data = JsonUtility.ToJson(DataBaseManager.DataBase[username]);
    3.         WWWForm form = new WWWForm();
    4.         form.AddField("name",username);
    5.         form.AddField("data", data);      
    6.         UnityWebRequest www = UnityWebRequest.Post("http://127.0.0.1/upload.php",form);
    7.         yield return www.Send();
    8.         if (www.isError)
    9.             Debug.Log(www.error);
    10.         else
    11.             Debug.Log("Uploaded");
    12.         Debug.Log(www.downloadHandler.text);
    13.     }
    Code (php):
    1. <?php    
    2.     if(isset($_POST['name']) && isset($_POST['data'])){
    3.         file_put_contents($_POST['name'].".txt", $_POST['data']);      
    4.         echo "uploaded.";
    5.     }else{
    6.         echo "invalid file uploaded.";
    7.     }  
    8. ?>
     
    bpetersonvalorem likes this.
  4. bpetersonvalorem

    bpetersonvalorem

    Joined:
    Jun 8, 2017
    Posts:
    5
    Ah! Life saver! Listen carefully to the above post people
     
  5. DoPie

    DoPie

    Joined:
    Jun 20, 2013
    Posts:
    64
    Hi can i used this to upload any files? like video or audio
     
  6. atagbuzc

    atagbuzc

    Joined:
    Aug 17, 2020
    Posts:
    1
    Hi MrSaoish, im currently trying to post some text files from my game to an online server like you did, but i keep getting an error saying DataBaseManager does not exist in this context. I am relatively new to programming and have made my way into the final stages of my game through multiple youtube videos, but this still proves to be a road block for me.

    Please help me out if you can.
     
  7. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    He hasn't logged into the forum in over a year and a half, so don't expect him to quickly respond. But DataBaseManager in the context of this code is just where he's getting the data from which he wants to upload to the server. You'd replace that with wherever you are getting the data from which you want to upload in your own code.