0

The issue is, I am trying to write to a file on the server as a response to a request initiated by the Client Browser. NOTE: It is a LONG time since I have worked on TypeScript / PHP / Servers so do NOT assume that I know a lot of stuff by default :-)

I have based my code on this example: /questions/11240996/write-javascript-output-to-file-on-server

I ended up with code that uses PHP on the server side to create the file "h.txt" in the https://objective.no/webapptest2/ folder The file h.txt an empty is indeed created, but its content "456" is never written: I get no error messages indicating why.

Below is my code for Client and Server Side

Server Side

//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);
}

(I tried to include proper Links to server etc, but the Post was then classified as SPAM?)

Is the problem that h.txt on the Server is Read Only for the Client? What is the solution?

I am expecting to be able to write text to the h.txt file on the server.

13
  • The problem is that none of the php code even attempts to read the posted data from the client side, let alone write it to the file. The code just creates an empty file, exactly as you told it to Commented Aug 1, 2023 at 17:56
  • Thanks. Could you please show me what's missing: As I said,. am way outside of my comfort zone here.... Commented Aug 1, 2023 at 17:58
  • Also the parameter you send from the client needs a name so php can identify it, e.g. text=456. Then php could get to it using $_POST["text"] and write that value into the file Commented Aug 1, 2023 at 17:58
  • Some tutorials about how to send data to php using fetch() (and from html forms in general) might benefit you Commented Aug 1, 2023 at 17:59
  • OK. If you check the link to the original example that I provided, you will see that originally no PHP code was used. I only provided the PHP code to create the h.txt file. The rest should work as in the original example, right? Commented Aug 1, 2023 at 18:02

1 Answer 1

0

Your code lacks three crucial but simple things:

  1. The client-side code doesn't correctly send a form-url-encoded string with a named parameter and a value. Currently you have the value, but there is no name by which PHP can identify it. The pattern is the same as you often see in URLs: name=value. (Multiple parameters would be written as name1=value1&name2=value2 ...etc.)

  2. The server-side PHP code makes no attempt to read anything that was submitted from the client side. PHP will place (correctly-written) form-url-encoded POST parameters in the $_POST array for your convenience.

  3. The PHP code also makes no attempt to actually write anything into the file. For this simple case, rather than messing about with separate calls to fopen etc. it's much easier to use file_put_contents so you can do the whole operation in one line.

With all that in mind, this should work:

JavaScript

testWriteToServerFile() {

        let data: string = "text=456";// this is your data that you want to pass to the server, with a parameter name in form-url-encoded format
        var url = "test.php"; //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.onreadystatechange = function() { //define a function to be called when the request's state changes.
            if (http.readyState == 4) { //if the state indicates the request is done
                alert(http.responseText); //show what the server sent back as its response
            }
        }
        //send the request with the data
        http.send(data);
}

test.php

<?php
file_put_contents("h.txt", $_POST["text"]);
echo "Saved submitted text to h.txt on the server";
?>
Sign up to request clarification or add additional context in comments.

4 Comments

Indeed this works! Thanks a LOT :-) To all posting answers: I am sorry for my confusion in my comments: Of course there should be a PHP file on the server!
Just a simple follow up question: Would it be possible to save the h.txt in the "assets" folder? I tried the following, but then no h.txt would be written: file_put_contents("/assets/h.txt", $_POST["text"]); // Not successfull
Yes you can. But you need to be mindful of the construction of the path. Did you get an error or warning message when you tried that code? It might simply be the path is wrong. The / at the start may be telling PHP to start from the root path, rather than relative to the current working folder, so try assets/h.txt instead and see if that helps (obviously it's a guess because I don't actually know where you made your assets folder relative to test.php). See phpdelusions.net/articles/paths to get your head around paths in PHP. The rest of that site is valuable resource too!
Once more, you are correct: assets/h.txt works like a charm :-) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.