2012-06-17 28 views
0

我是新來學習PHP和我的第一個程序之一,我想做一個基本的PHP網站與登錄功能與陣列的用戶和passwd。如何從php中的文件讀取每行?

我的想法是存儲用戶名作爲參數列表,並有passwd作爲內容,就像這樣:

arr = array(username => passwd, user => passwd); 

我現在的問題是,我不知道我怎樣才能從文件中讀取(data.txt),所以我可以將它添加到數組中。

data.txt sample: 
username passwd 
anotherUSer passwd 

我已經打開了文件,fopen並將其存儲在$data

+3

你不應該存儲敏感信息以明文形式。 – Norse

+0

在@Norse的建議之上,這可以很容易地搜索到。 'file_get_contents'和'split'會爲你做。 – Qix

+0

@Norse我知道我不應該以純文本存儲任何敏感信息,但這是我第一個真正的PHP程序,它只是爲了學習,我沒有看到讓它變得太複雜的觀點。我當然會添加一個加密,如果這將是一個真正的網站有一天。 – Alvar

回答

3

可以使用file()功能。

foreach(file("data.txt") as $line) { 
    // do stuff here 
} 
+0

這似乎是最簡單的解決方案,我應該用這個簡單的練習。謝謝! :) – Alvar

0

這適用於非常大的文件,以及:

$handle = @fopen("data.txt", "r"); 
if ($handle) { 
    while (!feof($handle)) { 
     $line = stream_get_line($handle, 1000000, "\n"); 
     //Do Stuff Here. 
    } 
fclose($handle); 
} 
4

修改這個PHP示例(從官方PHP站點採取... 總是首先檢查!):

$handle = @fopen("/path/to/yourfile.txt", "r"); 
if ($handle) { 
    while (($buffer = fgets($handle, 4096)) !== false) { 
     echo $buffer; 
    } 
    if (!feof($handle)) { 
     echo "Error: unexpected fgets() fail\n"; 
    } 
    fclose($handle); 
} 

到:

$lines = array(); 
$handle = @fopen("/path/to/yourfile.txt", "r"); 
if ($handle) { 
    while (($buffer = fgets($handle, 4096)) !== false) { 
     lines[] = $buffer; 
    } 
    if (!feof($handle)) { 
     echo "Error: unexpected fgets() fail\n"; 
    } 
    fclose($handle); 
} 

// add code to loop through $lines array and do the math... 

要知道,你應該不會將登錄詳細信息存儲在另外未加密的文本文件中,因此此方法存在嚴重的安全問題。 我知道你是PHP新手,但最好的方法是將其存儲在數據庫中,並用MD5或SHA1等算法加密密碼,

+0

當然最好是加密密碼,但因爲這只是爲了學習,我不會使用這個任何** REAL **網站這不是問題。 – Alvar

+0

我從來不理解這個例子,做這麼小的操作似乎太複雜了。 – Alvar

+0

@Alvar在許多語言中,這確實是一種相當常見的方法。你打開一個文件,得到一個* handle *(或多或少的一個指針),然後通過逐步推進來讀取和查找它。正如另一位用戶指出的那樣,您可以處理非常大的文件。 對於你來說,使用'file()'的用戶的答案就足夠了。 – Cranio

1

不應將敏感信息存儲爲明文,而應回答你的問題,

$txt_file = file_get_contents('data.txt'); //Get the file 
$rows = explode("\n", $txt_file); //Split the file by each line 

foreach ($rows as $row) { 
    $users = explode(" ", $row); //Split the line by a space, which is the seperator between username and password 
    $username = $users[0]; 
    $password = $users[1]; 
} 

Take a look at this thread.

0

使用文件()或file_get_contents()函數來創建數組或一個字符串。

過程中的文件內容需要

// Put everything in the file in an array 
$aArray = file('file.txt', FILE_IGNORE_NEW_LINES); 

// Iterate throug the array 
foreach ($aArray as $sLine) { 

    // split username an password 
    $aData = explode(" ", $sLine); 

    // Do something with the username and password 
    $sName = $aData[0]; 
    $sPass = $aData[1]; 
}