duan032225 2016-01-02 20:36
浏览 17
已采纳

使用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

  • 写回答

1条回答 默认 最新

  • douguanyan9928 2016-01-02 20:52
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败