0

I found a code here for saving a form to a text file. The problem is that it doesn't save the form to /tmp/mydata.txt. It says "xxx bytes written" but when I open the txt file I can't see the values I submitted.

Also what should I do to save the txt filenames dynamically like datesubmitted.txt for example.

<form action="myprocessingscript.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}
halfer
  • 19,824
  • 17
  • 99
  • 186
BB1907
  • 59
  • 1
  • 2
  • 6

1 Answers1

3

Following code should work for you:

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
    $filename = date('YmdHis').".txt";
    $ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}
?>

You can create file dynamically and check if its exist just write your content or create new.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Jaya Vishwakarma
  • 1,332
  • 1
  • 18
  • 36