My project requires contacting a PHP script hosted online. First the project should post a string to the PHP to be processed and returned from the PHP. So in my C#, I call UnityWebRequest.Post followed by UnityWebRequest.Get. Only the Post has issues. The Get request works perfectly as intended (the PHP returns a default set of data if the Post request doesn't do anything).
List<IMultipartFormSection> dataForm = new List<IMultipartFormSection>();
dataForm.Add(new MultipartFormDataSection("difficulty=Easy"));
UnityWebRequest www = UnityWebRequest.Post(webpage, dataForm);
yield return www.SendWebRequest();
This was the latest method I attempted using. Previously I used WWWForms and also tried to Post the string directly into the method. None of these worked. The Get request in Unity works fine, so I figured it might be the PHP that might be the problem.
$difficulty = $_POST["difficulty"];
if (!isset($difficulty)) {
$difficulty = "Hard";
}
But I wasn't convinced the PHP was broken since it works perfectly if $difficulty is set using the GET method through the URL (currently the project is using WebClient from System.Net and works perfectly which further convinces me that the PHP isn't the issue). So what's exactly the issue with UnityWebRequest.Post here?
My Answer:
One possible issue could be with how you are formatting the dataForm in your C# code. Make sure that the key-value pairs are separated by an ampersand (&) and that the key and value are separated by an equals sign (=).
Another issue could be with how you are accessing the data in your PHP script. Make sure that you are using the correct key to access the data that is being posted. In your PHP script, you are trying to access the data using $_POST["difficulty"], so make sure that the key "difficulty" matches the key that you are using in your C# code.
Additionally, make sure that the webpage variable in your C# code is set to the correct URL of your PHP script. Double check that the URL is correct and that the PHP script is accessible from your Unity project.
If you have tried all of these suggestions and are still experiencing issues, you may want to consider using a tool like Postman to test your PHP script and see if it is receiving the data correctly. This can help you determine if the issue is with your C# code or with the PHP script.
Rate this post
5 of 5 based on 6979 votesComments