1

This is my code:

<?php
                extract ($_POST);
                $fh = fopen ("./s.txt", "a");
                echo file_get_contents( "./s.txt" );
                if(($line = fgets($fh)) !== false) {}
                echo($line);
                file_put_contents("./signup.txt", "");

                if($line!=false && $line!='') {
                        echo '<script language="javascript">';echo 'alert($line)';echo '</script>';
                        fwrite ($fh, "$line \n");
                        $n = $line;
                }
                else {
                        fwrite ($fh, "$_POST[n] \n");
                        $n = $_POST[n];
                }
                fclose ($fh);

  $script = $_SERVER['PHP_SELF'];
  print <<<TOP
  <html>
  <body>
  <form method = "post" action = "$script">
  <table border = "1">
        <tr>
          <td> Name</td>
          <td> <input type = "text" value = "$n" name = "n" size = "30" /></td>
        </tr>

TOP;
  print <<<BOTTOM
  <tr><td><input type = "submit" name = "order" value = "Submit Order" /></td></tr>
  </table></form></body></html>
BOTTOM;
?>

Basically, this has one entry spot which someone can enter into, and once someone enters into it, the data is written to a file. Every time after that the page is loaded, the data should be read from the file and set as the value to the input.

But when I load the program, enter "Word" as the field, and press submit, then open a new tab (to ensure it's not just the data being saved) and reenter the URL, "Word" is echoed as file_get_contents, but nothing is echoed for echo($line) and nothing is in the field for the input.

Why is this and how can I fix it?

1 Answers1

1

While this doesn't appear to be documented explicitly/clearly in php.net (I'll provide links to relevant documentations below), having just run a test on my end, I've found that fgets() will always return false if you run it on a file resource where you used 'a' as the mode in fopen()

This I imagine is a side-effect of the 'a' mode opening the file for writing only. Running the exact same test, using 'a+' (Open the file for writing and reading) as the mode instead, has both fgets() and file_get_contents() output 'word'. The fopen documentation has details on the different modes.

http://php.net/manual/en/function.fopen.php

http://php.net/manual/en/function.fgets.php

And a couple screenshots of my testing this on my end, if you want to see the code I tested with and the results yourself:

Using mode 'a'

Using mode 'a+'

SierraKomodo
  • 365
  • 4
  • 12