Search code examples
c#phpdictionaryunity-game-engineserver

How do I send a two string Dictionary to a server?


I'm new to Unity (and c#, along with PHP) and have been tasked with getting some old c# and PHP code working. The code below is supposed to send the dictionary (formData) to the PHP server that then converts it to json. The code is below:

...
//This code runs for each file that is uploaded, the file is a list of strings and integers.
Dictionary<string, string> formData = new Dictionary<string, string>();
using (StreamReader sr = file.OpenText())
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    string[] data = s.Split(';');
                    uploadResultText.setText(file.Name + ":" + data[0] + " " + data[0]);
                    if (data[1] == "") data[1] = " ";
                    formData[data[0]] = data[1];
                }
            }
UnityWebRequest uploadRequest = UnityWebRequest.Post(serverBaseURL, formData);
currentUploadRequest = uploadRequest;
yield return uploadRequest.SendWebRequest();
...

If this code is working, how will I need to receive it server-side?


Solution

  • It turns out it was a server side error, the code above should work. The server was returning http error 500 because it was requesting data that did not exist (caused by switching names on the app side, but not the server side). The server side code uses $_POST to reference the incoming data, and a sample can be seen below.

    if (isSet($_POST["App"])) {
        $dataArray = array();
        foreach($expectedFormInputCommon as $input) {
            if (isSet($_POST[$input])) {
                if (seralizeString($_POST[$input]) !== false) {
                    $dataArray[$input] = seralizeString($_POST[$input]);
                } else {
                    http_response_code(400);
                    exit;
                    }
            } else {
                http_response_code(400);
                $_POST[$input] = "empty";
                exit;
            }
        }
    }