I'm a beginner, and I'm just doing something for fun. Does anyone know how I can append data to a local text file on the server side? I would rather use JavaScript, but I can use PHP, and it would be perfect if I could call the function like this:
appendData(data, fileName);
Thanks!
If you're using a PHP server, you can do something like this in php:
file_put_contents("/path/to/file", file_get_contents("/path/to/file") . $data);
You can't do this with browser JavaScript directly. This is because browser javascript runs on the browser and not on the server.
If you're running a node.js server (which is a JavaScript server and is different from JavaScript running on a browser) you can do something like below. See this answer.
var fs = require("fs"); // Get file system
fs.appendFile('message.txt', 'data to append', function (err) {
});
If the file is huge you may not want to go the file_get_contents route (since it has to read the entire file and then write it out. You could do:
$fp = fopen($filename,"a");
fwrite($fp,$data);
"a" positions the pointer at the end for appending. If you don't mind cheating:
`echo $data >> $filename`;
which escapes to the shell.