16

我在这个网站上搜索了一个答案,但找不到任何答案。

我有一个表格,我想将输入的内容写入一个 txt 文件。为了简单起见,我只写了一个简单的表单和一个脚本,但它总是让我看到一个空白页。这是我得到的

<html>
<head>
    <title></title>
</head>
<body>
    <form>
        <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>
    <a href='data.txt'>Text file</a>
</body>

这是我的 PHP 文件

<?php
$txt = "data.txt"; 
$fh = fopen($txt, 'w+'); 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
   $txt=$_POST['field1'].' - '.$_POST['field2']; 
   file_put_contents('data.txt',$txt."\n",FILE_APPEND); // log to data.txt 
   exit();
}
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file
    ?>
4

5 回答 5

45

您的表单应如下所示:

<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

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\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');
}

我写信是/tmp/mydata.txt因为这样我就可以确切地知道它在哪里。使用data.txt写入当前工作目录中的该文件,在您的示例中我一无所知。

file_put_contents为您打开、写入和关闭文件。不要惹它。

进一步阅读: file_put_contents

于 2013-02-21T10:06:04.010 回答
5

您遇到的问题是因为<form>您拥有额外的数据,您的数据进入GET方法,并且您正在PHP使用POST.

<body>
<!--<form>-->
    <form action="myprocessingscript.php" method="POST">
于 2013-02-21T09:47:20.107 回答
0

一个可能的解决方案:

<?php
$txt = "data.txt"; 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
    $fh = fopen($txt, 'a'); 
    $txt=$_POST['field1'].' - '.$_POST['field2']; 
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file
}
?>

您在关闭 de 文件之前关闭了脚本。

于 2013-02-21T09:47:32.767 回答
0

如果您使用 file_put_contents,则无需执行 fopen -> fwrite -> fclose,file_put_contents 将为您完成所有这些。您还应该检查网络服务器是否在您尝试写入“data.txt”文件的目录中具有写入权限。

根据您的 PHP 版本(如果它是旧的),您可能没有 file_get/put_contents 函数。检查您的网络服务器日志以查看执行脚本时是否出现任何错误。

于 2013-02-21T09:48:25.660 回答
0

使用fwrite()而不是 file_put_contents()

于 2013-02-21T09:48:38.187 回答