PHP将文件从input文件写入到txt

我已经search周围的这个网站的答案,但没有find任何。

我有一个表单,我想获取input的内容写入一个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 ?> 

你的表单应该是这样的:

 <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'] . "\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打开,为您写入和closures文件。 不要乱它。

进一步阅读: file_put_contents

你所遇到的问题是因为你有额外的<form> ,你的数据是用GET方法进行的,而你正在使用POST来访问PHP的数据。

 <body> <!--<form>--> <form action="myprocessingscript.php" method="POST"> 

可能的解决scheme:

 <?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 } ?> 

在closures文件之前,您正在closures脚本。

如果你使用file_put_contents,你不需要做fopen – > fwrite – > fclose,那么file_put_contents会为你做所有的事情。 您还应该检查Web服务器是否在写入“data.txt”文件的目录中有写权限。

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

使用fwrite()而不是file_put_contents()