从 TypeScript/Angular 客户端写入服务器端文本文件(由客户端创建)时出现问题

问题描述 投票:0回答:1

问题是,我试图写入服务器上的文件作为对客户端浏览器发起的请求的响应。 注意:自从我从事 TypeScript / PHP / 服务器工作以来已经很长时间了,所以不要以为我默认知道很多东西:-)

我的代码基于此示例: /questions/11240996/write-javascript-output-to-file-on-server

我最终得到了在服务器端使用 PHP 的代码在 https://objective.no/webapptest2/ 文件夹中创建文件“h.txt” 确实创建了一个空文件 h.txt,但其内容“456”从未被写入:我没有收到任何指示原因的错误消息。

下面是我的客户端和服务器端代码

服务器端

//PHP code:  (A little elaborate, but it should work)

//h.txt is created, but its content is never written: read only problem?? I can't find how to see if //the file is read only or not)

//The php Code is located on Server

<?php
function getData() {
  $myFile = fopen("h.txt", "w");
  fclose($myFile);
  sleep(5);
  //return "link to h.txt";
}
getData();

// Tried to return different values for the URL below: 
// "h.txt" is created, but its content "456" is never // written

return "URL to h.txt";
?>
//On the Client side I have the following code:
//The Client is written in Angular, and the function that triggers the data exchange with server

testWriteToServerFile() {

        let data: string = "456";// this is your data that you want to pass to the server 
        //next you would initiate a XMLHTTPRequest as following (could be more advanced):

        var url = url to the server side PHP code that will receive the data.

        var http = new XMLHttpRequest();
        http.open("POST", url, true);

        //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", data.length.toString());
        http.setRequestHeader("Connection", "close");

         http.onreadystatechange = function() {//Call a function when the state changes.
            if(http.readyState == 4 && http.status == 200) {
                alert(http.responseText);//check if the data was received successfully.
            }
        }
        http.send(data);
}

(我试图包含到服务器等的正确链接,但是 该帖子随后被归类为垃圾邮件?)

服务器上的h.txt对于客户端来说是只读的问题吗? 解决办法是什么?

我希望能够将文本写入服务器上的 h.txt 文件。

php typescript server file-access
1个回答
0
投票

在这里,您打开一个带有写入选项的文本文件,然后立即关闭它

function getData() {
  $myFile = fopen("h.txt", "w");
  fclose($myFile);
  sleep(5);

您实际需要做的是将内容写入您发布到网址的数据变量中,如下所示:

function getData() {
$myFile = fopen("h.txt", "w");
fwrite($myFile, filter_input(INPUT_POST, 'data', FILTER_SANITIZE_SPECIAL_CHARS));
fclose($myFile);

我个人更喜欢 input_put_content() 而不是 fopen/fclose

© www.soinside.com 2019 - 2024. All rights reserved.