Hi I have been making an app in Unity and I have been trying to add code that will log User actions i.e. they have made a certain game object appear. What I am trying to do is write to a .txt file stored on a server I have the following code which is based on:
http://answers.unity3d.com/questions/984290/upload-txt-file-to-server-using-php.html
and they suggest it works, for me it is not writing anything to the file.
Here is my PHP code (SaveData.php):
<?php
$Action = $_GET["action"];
$Date = date('Y/m/d H:i:s');
$myFile = "TestingData.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh,$Action . "," . $Date . "
");
fclose($fh);
?>
And here is the C# (SaveData.cs) I am attaching to the game objects I change the Action value in the inspector window:
using UnityEngine;
using System.Collections;
public class SaveData : MonoBehaviour {
public string postDataURL = "http://arinstructionman.byethost7.com/SaveData.php?"; //add a ? to your url
public string Action;
void Start()
{
StartCoroutine(PostData(Action));
}
IEnumerator PostData(string action)
{
string post_url = postDataURL + "action=" + WWW.EscapeURL(action);
WWW data_post = new WWW(post_url);
yield return data_post;
if (data_post.error != null)
{
print("There was an error saving data: " + data_post.error);
}
}
}
If I copy the post_url value and run it in the browser it seems to work fine, can anyone advise what I am doing wrong?
post_url output:
http://arinstructionman.byethost7.com/SaveData.php?action=Plane+Visible
Any help is much appreciated.
I would suggest trying this with $_POST
instead of $_GET
and see if you get a different response.
Also, you can use file_put_contents
to open, write, and close the file all in one line, and using the FILE_APPEND
flag to prevent overwriting the existing file. If the file does not exist, this will also create the file for you.
<?php
if(!isset($_POST["action"]))
{
echo ("NO DATA RECIEVED");
return;
}
$action = $_POST["action"];
$date = date('Y/m/d H:i:s');
$data = "{$action},{$date}
";
$myFile = "TestingData.txt";
if(file_put_contents($myFile, $data, FILE_APPEND))
echo ("success");
else
echo ("failed to write file);
?>
And use WWWform
to POST
data to the PHP file:
public string postDataURL = "http://arinstructionman.byethost7.com/SaveData.php";
public string Action = "some action";
void Start()
{
StartCoroutine(PostData(Action));
}
IEnumerator PostData(string action)
{
WWWForm form = new WWWForm();
form.AddField("action", action);
WWW dataPost = new WWW(postDataURL, form);
yield return dataPost;
if (dataPost.error != null)
print("There was an error saving data: " + data_post.error);
else
print(dataPost.text);
}