簡體   English   中英

如何從php文件中讀取每一行?

[英]How do I read each line from a file in php?

我是學習php的新手,在我的第一個程序中,我想創建一個基本的php網站,該網站具有登錄功能,並具有用戶和passwd的數組。

我的想法是將用戶名存儲為列表參數,並將passwd作為內容,如下所示:

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

現在我的問題是我不知道如何讀取文件( data.txt ),因此無法將其添加到數組中。

data.txt sample:
username passwd
anotherUSer passwd

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

修改此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等算法對密碼進行加密,

您可以使用file()函數。

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

您不應該將敏感信息存儲為純文本格式,而是要回答您的問題,

$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];
}

看一下這個線程。

這也適用於超大文件:

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

使用file()或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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM