- Home /
Append text file online
I am using the following code to write text files to my server, but I need the ability to append to a text file on the server. Do I need to change something in the code below or to the php file?
Unity code below:
using UnityEngine; using System.Collections;
public class SaveOnline : MonoBehaviour {
public string postDataURL = "http://magneticstudio.com/saveonename.php?"; //add a ? to your url
public string Playername;
public string Playerdata;
void Start()
{
Playername = "PlayerName";
Playerdata = "peter,lacalamita,ppp@ttt.com";
StartCoroutine(PostData(Playername,Playerdata));
}
IEnumerator PostData(string name, string data)
{
//This connects to a server side php script that will write the data
string post_url = postDataURL + "name=" + WWW.EscapeURL(name) + "&data=" + data ;
// Post the URL to the site and create a download object to get the result.
WWW data_post = new WWW(post_url);
yield return data_post; // Wait until the download is done
if (data_post.error != null)
{
print("There was an error saving data: " + data_post.error);
}
}
}
PHP code below:
<?php
$name_to_save = $_GET["name"];
$data_to_save = $_GET["data"];
$myFile = $name_to_save . ".txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh,$data_to_save);
fclose($fh);
?>
Answer by KwahuNashoba · Jul 09, 2016 at 04:29 AM
You have to edit that php to append file if the file already exists or to write new file if there is no file with that name, like it does now. But I would keep this endpoint just in case you want to overwrite file for some reason. So keep this and write another one that will append text
Answer by gorsefan · Jul 09, 2016 at 01:00 PM
This is so not a Unity question.
change
$fh = fopen($myFile, 'w') or die("can't open file");
to
$fh = fopen($myFile, 'a') or die("can't open file");
to append to the file. See [fopen][1].
Your answer
