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.

brombeer
  • 8,716
  • 5
  • 21
  • 27
GOS
  • 3
  • 2
  • 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 – ADyson Aug 01 '23 at 17:56
  • Thanks. Could you please show me what's missing: As I said,. am way outside of my comfort zone here.... – GOS Aug 01 '23 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 – ADyson Aug 01 '23 at 17:58
  • Some tutorials about how to send data to php using fetch() (and from html forms in general) might benefit you – ADyson Aug 01 '23 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? – GOS Aug 01 '23 at 18:02
  • No. Because you need to name the parameter so php can see and identify it (since it can cope with multiple parameters being sent). Not the same as just writing content directly to a file (which isn't secure at all) – ADyson Aug 01 '23 at 18:04
  • Maybe it would be better to only use PHP to write the contents, but unfortunately I do not know how to do this. 5+ years since I have done any PHP / server programming, and never any "advanced :-( – GOS Aug 01 '23 at 18:05
  • I initially had no PHP code: I just used it to create the file. If I create the file in advance, then the Client Side code should work, according to the example, but it did not work for me. So the problem seems to be my Client Side TypeScript code? (if we forget about the PHP for a while) – GOS Aug 01 '23 at 18:09
  • It depends _why_ it didn't work...most likely you don't have permission to directly write files to the webserver from the client side (which if you think about it, is a _really, really_ good thing, otherwise anyone could upload any old junk to your website). – ADyson Aug 01 '23 at 21:48
  • P.S. ... `If you check the link to the original example that I provided, you will see that originally no PHP code was used`...if you're referring to [this answer](https://stackoverflow.com/a/11241093/5947043) then that statement isn't correct. `var url = "get_data.php";` is clearly intended to point to a PHP script. The author just didn't specify what to put in the PHP file, that's all. [this answer](https://stackoverflow.com/a/11241115/5947043) from the same question shows how to do the client _and_ PHP side, only difference is the client-side uses jQuery but you can replace that with XHR – ADyson Aug 01 '23 at 21:51
  • P.P.S. `and never any "advanced`...I appreciate it's been a while, and we all forget stuff, but absolutely nothing about this is remotely "advanced" in any way, and it's all google-able really :-) – ADyson Aug 01 '23 at 21:59
  • `I tried to include proper Links to server etc, but the Post was then classified as SPAM`...yep - please read https://meta.stackoverflow.com/questions/254428/something-in-my-web-site-or-project-doesnt-work-can-i-just-paste-a-link-to-it – ADyson Aug 01 '23 at 21:59
  • `Is the problem that h.txt on the Server is Read Only for the Client?`...no, in the sense that you're not sending a request directly to it (the request goes to the PHP script), but yes in the sense that I really hope it is, otherwise you've got big security problems (as I mentioned earlier) – ADyson Aug 01 '23 at 22:00

1 Answers1

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";
?>
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 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! – GOS Aug 02 '23 at 06:22
  • 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 – GOS Aug 02 '23 at 06:55
  • 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 https://phpdelusions.net/articles/paths to get your head around paths in PHP. The rest of that site is valuable resource too! – ADyson Aug 02 '23 at 09:23
  • 1
    Once more, you are correct: assets/h.txt works like a charm :-) Thanks! – GOS Aug 02 '23 at 16:21