2014-02-19 71 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