Search code examples
c#phpunity-game-enginepostunitywebrequest

Get the link of the uploaded file with UnityWebRequest and php


I want to allow the user to use a local image from his machine and upload it to the server.

What I did is use UnityWebRequest in-game, load the image, send it to a PHP file on the server, and wait for the reply to remember the URL where the file si saved(to save it in Playfab later).

This is the code I made so far:

private readonly string setAvatarUrl = "http://myurl.com/setavatar.php";

private readonly string playerIdField = "playfabid";
private readonly string imageField = "img_avatar";

public IEnumerator SaveImageToDB(Texture2D image)
    {
        byte[] bytes = image.EncodeToPNG();

        WWWForm form = new WWWForm();
        form.AddField(playerIdField, player.playerId);
        form.AddBinaryData(imageField, bytes, "avatar.png", "image/png");

        UnityWebRequest www = new UnityWebRequest();
        www = UnityWebRequest.Post(setAvatarUrl, form);

        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.LogError(www.error);
        }
        else
        {
            string jsonFromDB = www.downloadHandler.text;    // Return empty string
            string imageUrl = JsonUtility.FromJson<string>(jsonFromDB);

            Debug.Log($"JSON returned: {jsonFromDB}");

            if (!string.IsNullOrEmpty(imageUrl))
            {
                // Save the url
            }

            Debug.Log("Image upload complete!");
        }

    }

And this is the PHP file:

    <?php
ini_set('display_errors',1);
$idplayfab = $_POST['playfabid'];

$path = 'avatar/'.$idplayfab;
if(file_exists($path)) {
    //dir exist
    $files = glob($path.'/*');
    foreach($files as $file){
        if(is_file($file))
            unlink($file);
    }
} else {
    //not exist
    mkdir($path);
}

$uploadfile = $path ."/". basename($_FILES['img_avatar']['name']);
if (move_uploaded_file($_FILES['img_avatar']['tmp_name'], $uploadfile)) {
    $array = array('result' => 'ok', 'url' => 'http://myurl.com/'.$uploadfile);
    $json = json_encode($array);
    return $json;
} else {
    $array = array('result' => 'ko');
    $json = json_encode($array); 
    return $json;
}
?>

The image is saved on the server but the problem is when I try to get the JSON to get the URL, the string is empty and I don't understand why.

I tried tons of solutions like this one or this one but I cannot figure it out.

I also tried to use the deprecated WWW instead, but still, it doesn't work.

I'm kinda new to PHP so maybe it could be the PHP part the problem I believe.


Solution

  • Not an PHP expert but:

    Afaik return is only used to evaluate certain functions e.g. for success or in order to further handle the result of something before responding to the client on server side.

    What you want to do is rather sending your content as the http result to the client

    => You should rather use echo or print which is used to generate the http output.