真正简单的Php表单保存到文本文件

时间:2016-01-06 19:17:58

标签: php forms

我在这里找到了一个代码,用于将表单保存到文本文件中。问题是它不会将表单保存到/tmp/mydata.txt。它说“写了xxx字节”但是当我打开txt文件时,我看不到我提交的值。

另外,如何动态保存txt文件名,例如datesubmitted.txt

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

1 个答案:

答案 0 :(得分:1)

以下代码应该适合您:

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

您可以动态创建文件,并检查其是否存在只是编写您的内容或创建新内容。