繁体   English   中英

HTML表单保存到服务器端文本文件

[英]HTML Form save to server-side text file

所有。

我发现了许多脚本,它们可以将表单输入保存到本地计算机,即IE下载包含提交信息的文本文档,但是我正在尝试开发一个HTML表单,当按下“提交”按钮时,该表单可以保存文本在文本字段中作为单个文本文档。 我最接近的是以下内容(很抱歉,无法找到我最初从何处获得此代码。希望没关系:/)

<html>
<head>
<script>
$myFile = "testFile.txt";
if(isset($_POST['fileWrite']) && !empty($_POST['fileWrite'])) {
$fileWrite = $_POST['fileWrite'];
}
if($fileWrite) {
$fh = fopen($myFile, 'a') or die("can't open file"); //Make sure you have permission
fwrite($fh, $fileWrite);
fclose($fh);
exec('/your/command /dev/null 2>/dev/null &');
}
</script>
</head>

<body>
<form id="some" name="someName" method="post" action="/../PastEntries/file.txt">
<input type="text" id="some1" class="someClass" value="" name="fileWrite"/>
<input type="submit" value="submit" class="submitClass"/>
</form>
</body>
</html>

但是,我收到错误消息“无法发布/../www/file.txt”
我是PHP新手,不知道如何解决此问题。 希望更有经验的人可以提供帮助或替代方案!
提前致谢!

未经测试,但您可以执行类似的操作。 表单动作将被完全删除,因此表单会在同一页面上发布-请求由PHP解释,并将数据写入文本文件。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        $filename=__DIR__ . '\\file.txt';
        file_put_contents( $filename, implode( PHP_EOL,$_POST ) . PHP_EOL, FILE_APPEND );
        exit();
    }
?>
<!doctype html>
<html>
    <head>
        <title>Save Form data to text file</title>
    </head>
    <body>
        <form id="some" name="someName" method="post">
            <input type="text" id="some1" class="someClass" value="" name="fileWrite"/>
            <input type="submit" value="submit" class="submitClass"/>
        </form>
    </body>
</html>

我一直在摆弄你的代码,看看我是否可以使它工作。 下面是固定版本。

<html>
<head>

<?php

$fileWrite = '';    
$myFile = "testFile.txt";
if(isset($_POST['fileWrite']) && !empty($_POST['fileWrite'])) {
$fileWrite = $_POST['fileWrite'].PHP_EOL;
}
if($fileWrite) {
$fh = fopen($myFile, 'a') or die("can't open file"); //Make sure you have permission
fwrite($fh, $fileWrite);
fclose($fh);
}
?>

</head>

<body>
<form id="some" name="someName" method="post">
<input type="text" id="some1" class="someClass" value="" name="fileWrite"/>
<input type="submit" value="submit" class="submitClass"/>
</form>
</body>
</html>

我已经解决了@RamRider先前指出的问题,并添加了.PHP_EOL来启用新的换行符( 请查阅手册以获得更好的理解 )。 使用此代码,让我们知道是否有任何错误。 我会尽我所能。

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM