0

I'm doing a UnityWebrequest and it's working fine, but upon checking what's is the post in my PHP I found that the post is an empty array and the file is aswell. I found a StackOverflow post that has a similar problem. But it's solution did not work for me. So why is the post and file empty? I'm running this on a local server.

UnityWebRequest POST to PHP not work

Web request

static IEnumerator Post(string url, string bodyJsonString)
{
    UnityWebRequest request = new UnityWebRequest(url, "POST");
    request.chunkedTransfer = false;
    Debug.Log(bodyJsonString);
    byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
    request.uploadHandler = new UploadHandlerRaw(bodyRaw);
    Debug.Log(request.uploadHandler.data.Length);
    request.downloadHandler = new DownloadHandlerBuffer();
    request.SetRequestHeader("Content-Type", "application/json");
    yield return request.SendWebRequest();
    Debug.Log("Status Code: " + request.responseCode);
    Debug.Log(request.downloadHandler.text);
}

Php

<?php
echo "POST: ";
print_r($_POST);
var_dump($_POST);

echo "Files: ";
print_r($_FILES);
var_dump($_FILES);

Debugs

{"testJson":1}

8

Status Code: 200

POST: Array ( ) array(0) { } Files: Array ( ) array(0) { }

anonymous-dev
  • 2,897
  • 9
  • 48
  • 112

2 Answers2

0

I had the same problem and this worked for me.

after

UnityWebRequest request = new UnityWebRequest(url, "POST");

add

request.chunkedTransfer = false;

The thing that had me stumped for ages was I needed to have the filename in the url. I was using index.php so I was just using the directory path for the url. Soon as I used the path including the filename it started working fine.

0

The problem was solved when I added content via a WWWForm. Then the $_Post array was populated.

https://docs.unity3d.com/ScriptReference/WWWForm.html

anonymous-dev
  • 2,897
  • 9
  • 48
  • 112