1

I'm trying to save a variable to a text file using PHP code. Everything else works apart from line 33 of my code, where I try and pass an HTML variable into PHP, in order to save that variable to my text file. Wouldn't like to use forms as I don't want to change my earlier code round too much as it's taken me ages to get it to work.

Have already tried, $_GET and $_REQUEST

<DOCTYPE.html>
<html>

<body>

<h3>Please enter your UN and PW</h3>

<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>

<script>
var username, password, x, INput;
username = prompt("Username: ");
password = prompt("Password: ");
document.getElementById("demo").innerHTML= "UN: " + username;
document.getElementById("demo1").innerHTML = "PW: " + password;

x = (password<=0) ? "No":"Yes";
document.getElementById("demo2").innerHTML = "Typed password: " + x;

INput= String(username + ", " + x + "\n" )
alert(INput);

</script>


<?php

    // Open the text file
    $f = fopen("textfile.txt", "a");

    // Write text line
    fwrite($f, #######); 

    // Close the text file
    fclose($f);

?>


</body>
</html>

The "##s" are where I would like "INput" to go, but it doesn't work as it is an html variable.

Expected Output: INput will save to the "textfile.txt" file

Actual Output: "Notice: Use of undefined constant INput - assumed 'INput' in /storage/ssd1/856/9172856/public_html/UNPW.php on line 33"

EDIT: Using 000webhost.com, if this changes anything

Cate Smith
  • 23
  • 4
  • You're gonna need AJAX for that, or you need to submit the form. –  Apr 07 '19 at 20:43
  • Actually, probably just AJAX –  Apr 07 '19 at 20:44
  • @Chipster could you give an example for how I could use this in this context? – Cate Smith Apr 07 '19 at 20:45
  • I'm not at a place I can do that at the moment (I'm on a phone right now) but I can when I get a chance if someone doesn't do it before I can. –  Apr 07 '19 at 20:48
  • @Chipster thank you for your kind help – Cate Smith Apr 07 '19 at 20:50
  • 1
    Here is a php / ajax example https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php – Keith Apr 07 '19 at 21:04
  • Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – miken32 Apr 08 '19 at 19:14

1 Answers1

0

The easiest way to make AJAX in Javascript is to use the Fetch function. There are lots of examples available on the web, but here's what I use:

side1.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h3>Please enter your UN and PW</h3>
  <p id="demo"></p>
  <p id="demo1"></p>
  <p id="demo2"></p>

  <script>
    var username, password, x, INput;

    username = prompt("Username: ");
    password = prompt("Password: ");

    document.getElementById("demo").innerHTML = "UN: " + username;
    document.getElementById("demo1").innerHTML = "PW: " + password;

    /* -----------------------------------------------------------------------
    x = (password <= 0) ? "No" : "Yes";
    document.getElementById("demo2").innerHTML = "Typed password: " + x;

    INput = String(username + ", " + x + "\n")
    alert(INput);
    ----------------------------------------------------------------------- */

    fetch("side2.php", {
      credentials : "same-origin",
      method      : "POST",
      headers     : { "Content-Type": "application/json" },
      body        : JSON.stringify(
                    {
                      "Username": username,
                      "Password": password
                    })
    })
    .then(response => response.json())
    .then(data=>{
      if (data.status == 'good world :)')
      {
        document.getElementById("demo2").innerHTML = data.User_Psw;
      }
      else 
      {
        document.getElementById("demo2").innerHTML = '??? it was so easy, what did you miss?';
      }
    })
  </script>
</body>
</html>

side2.php

<?php
mb_internal_encoding("UTF-8");  // old security story,
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';

$ReturnInfo = array();
$ReturnInfo['status'] = 'bad world :/';

if ($contentType === "application/json") {
  //Receive the RAW post data.
  $content = trim(file_get_contents("php://input"));

  $decoded = json_decode($content, true);

  $User = $decoded['Username'];
  $Pwd  = $decoded['Password'];

  // write data in a File...
    $fp = fopen('data.txt', 'wb');
    fwrite($fp, "last connected user info =\n");
    fwrite($fp, 'Username='.$User."\n");
    fwrite($fp, 'Password='.$Pwd."\n");
    fclose($fp);

  $ReturnInfo['status']   = 'good world :)';
  $ReturnInfo['User_Psw'] =  $User.'<=>'.$Pwd;

  //If json_decode failed, the JSON is invalid.
  //if(! is_array($decoded)) { ......
}
header("Cache-Control: no-cache, must-revalidate"); // force reset cache
header("Expires: Mon, 26 Jul 2000 05:00:00 GMT"); 

header('Content-type: application/json');
echo json_encode($ReturnInfo);
exit(0);
?>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • Your example doesn't write to a file. –  Apr 08 '19 at 01:05
  • @Chipster Writing to a file is not the most complicated, but I added it in my code – Mister Jojo Apr 08 '19 at 01:29
  • I know. I'm just saying because the OP asked for an example in context, and the context included writing a file. At any rate, it's all good now. :D –  Apr 08 '19 at 03:04
  • Am I right in storing the 2 sets of code in separate files, the first in a .html and the second in a .php file? – Cate Smith Apr 08 '19 at 08:11
  • Yes, this is AJAX, you do not leave your html page, you send/retrieve your values ​​to the server who is responding inside your page. This call is asynchronous (the A stand for Asynchronous, [+ JavaScript and XML]), so during this call, your page is not freezed and can continue other processes, interact with the user. When the server responds, it becomes a new process that the browser processes as a new interaction. if you want to put rules on the ordering of the different interractions, you have to use the mechanism of the promises; – Mister Jojo Apr 08 '19 at 13:30
  • https://en.wikipedia.org/wiki/Ajax_(programming) => AJAX . https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise => Promise . (XML is not longer in favor, and most of programmers [like me] use JSON in place, but this technology continue to be named AJAX) – Mister Jojo Apr 08 '19 at 13:31
  • @Cate Smith sorry for this 3th post, but I think it's better to fix this point. When the server, here with the help of the PHP interpreter, composes a html page for one (or several million) users, it does not keep any magic link with each of these pages. either the user starts the call of an entire page with possibly useful values, or he launches an AJAX call with just these useful values, but it is then up to the javascript interpreter to process the response from the server. – Mister Jojo Apr 08 '19 at 16:48