BB1907 BB1907 - 4 years ago 249
PHP Question

Really Simple Php Form To Save To A Text File

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

Answer Source

Following code should work for you:

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
    $filename = date('YmdHis').".txt";
    if (!file_exists($filename)) {
        $fh = fopen($filename, 'w') or die("Can't create file");
    }
    $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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download