2014-02-19 73 views
0

我需要你的帮助。 我需要每次将代码存储在txt文件中的信息,然后每个新记录到新行,以及应该做什么都被编号? 需要帮助 - php保存.txt

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

+0

它仅仅是一个例子 – lolspy

+1

萨穆埃尔,如果​​他正在求救保存的文本文件中,OP或者是新的编程或PHP新手。这是如何帮助他们的? –

+0

@HarryTorry你习惯的东西很难抹去。就个人而言,如果有人遇到了SQL查询无法正常工作的问题,并且不知道他很容易进行sql注入,我仍然指出这一点。我会试着暗示,如果代码工作并不意味着它应该被使用。但你是对的,我应该让这个选项更清楚。感谢您指出。 – Samuel

回答

0

你可以在一个更简单的方法做这样的..

<?php 
$txt = "data.txt"; 
if (isset($_POST['Password']) && file_exists($txt)) 
    { 
     file_put_contents($txt,$_POST['Password'],FILE_APPEND); 
    } 
?> 
0

我们打开文件写入到它,你必须把手a+ php doc 所以,你的代码将是:

<?php 
$fileName = "data.txt"; // change variable name to file name 
if (isset($_POST['Password'])) { // check if both fields are set 
    $file = fopen($fileName, 'a+'); // set handler to a+ 
    $txt=$_POST['Password']; 
    fwrite($file,$txt); // Write information to the file 
    fclose($file); // Close the file 
} 
?> 
+1

'w'将文件指针放在文件的开头,并将文件截断为零长度。你只会保存最后一个密码。 – manta

1

添加了一些注释来解释更改。

<?php 
$file = "data.txt"; // check if both fields are set 
$fh = fopen($file, 'a+'); //open the file for reading, writing and put the pointer at the end of file. 

$word=md5(rand(1,10)); //random word generator for testing 
fwrite($fh,$word."\n"); // Write information to the file add a new line to the end of the word. 

rewind($fh); //return the pointer to the start of the text file. 
$lines = explode("\n",trim(fread($fh, filesize($file)))); // create an array of lines. 

foreach($lines as $key=>$line){ // iterate over each line. 
    echo $key." : ".$line."<br>"; 
} 
fclose($fh); // Close the file 
?> 

PHP

fopen

fread

explode