簡體   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