kodabear
kodabear

Reputation: 340

Saving a file on server using JavaScript

Js code

var server = '';
var orig_chat = chatUpdateSucess;
chatUpdateSucess = function(o){
if (o.GlobalChats && o.GlobalChats.length > 0) {
    //TODO: Add setting to enable/diosable this
    console.log(JSON.stringify(o.GlobalChats));

    var xhr = new XMLHttpRequest();
    xhr.open("POST", server+"/api.php?request=log_gc");
    xhr.send(JSON.stringify(o.GlobalChats));

}
orig_chat.apply(this, arguments);
};

Server code named api.php

<?php 
header("Access-Control-Allow-Origin: *");
if(!empty($_POST['o.GlobalChats'])){
 $data = $_POST['o.GlobalChats'];
 $fname = time() . ".txt";//generates random name

  $file = fopen("" .$fname, 'w');//creates new file
   fwrite($file, $fclose($file);
  }

 ?>

console.log output [{"PlayerId":237186,"toPlayerId":0,"chatid":16606292,"added":"/Date(1451764948837)/","addedText":"20:02","PlayerLink":"p=Kodabear|237186|T?|78|1|0|0-144-0-240-186-0-0-0-0-0-0-0-0|#IKnowAFighter|Neurofibromatosis Awareness day/Month|5-404-282-59","text":"Exmaple of a real chat"}]

I created a js that sends a file to my server every time the chat in the game is updated. But I am having problems with the server side code any advice would be great help. (PHP code was founded here

Saving a text file on server using JavaScript

Upvotes: 0

Views: 202

Answers (1)

caulitomaz
caulitomaz

Reputation: 2331

Try to var_dump($_POST['o.GlobalChats']) to see if your data is reaching the server.

It seems like you are not writing the file to the system properly. Please read the examples at the manual (http://php.net/manual/pt_BR/function.fwrite.php)

Also, using time() is not safe, because two files may be created at the same UNIX timestamps in extreme cases, and one will overwrite the other

Try something like this:

$data = $_POST['o.GlobalChats'];

$fname = time() . "-" . rand ( 1 , 10000 ) . ".txt";

$handle = fopen($fname, 'w');

fwrite($handle, $data);

fclose($handle);

Upvotes: 3

Related Questions