2015-02-09 91 views
1

我使用explode()將從文本文件讀取的字符串轉換爲數組,我使用該數組與用戶的輸入進行比較。php比較兩個密碼字符串

文本文件包含:

user#test //user= username test= password 

當我嘗試使用STRCMP()返回-1,即使與

test||test 
=-1 

我打印輸出打印兩個字符串變量結果與:

if(isset($user_details[1])){ 
$user_details = explode('#', $user);  // $user is text file 
$passW = $_GET['password'];    // input: "test" 
$tesPW = user_details[1]; 
printf($passW."||".$testPW."=".strcmp($passW,$testPW)); 
} 
+1

你永遠不應該比較明文密碼。 http://php.net/manual/en/faq.passwords.php – zerkms 2015-02-09 21:35:07

+7

您使用'printf'語句將所有內容打印在一行上,但它在兩行輸出。這告訴我'$ testPW'以換行符 – 2015-02-09 21:35:20

+0

結尾嘗試使用'$ tesPW = trim(user_details [1]);' – 2015-02-09 21:44:47

回答

2

假設這是一個簡單的應用程序在一個有限的環境中選擇一組人,我會避免評論有關這種方法的安全問題。

如果用戶/通過匹配文件中的一行,則該函數將返回true,如果不匹配,則返回false

//Assumes const USERACCOUNTFILE defines the path to the file 
function AuthenticateUser ($username, $password) { 
    $handle = @fopen(USERACCOUNTFILE, "r"); //Open the file for reading 
    if ($handle) { 
     while(($line = fgets($handle)) !== false) { //Read each line of the file 
      $line = explode('#', $line); //Split the line 
      if($line && count($line) == 2) { //Does the line have the expected number of values? 
       //Compare the values minus all whitespace 
       if(trim($line[0], "\r\n\t ") == $username && trim($line[1], "\r\n\t ") == $password) { 
        fclose($handle); 
        return true; //Found a match 
       } 
      } 
     } 
    } 
    fclose($handle); 
    return false; //None matched 
} 

您也可以使用trim($line[0])"\r\n\t "可選參數,足夠的默認參數。

+0

你可以跳過'\ r \ n \ t'部分,因爲默認情況下trim會刪除它們,實際上列表是''\ t \ n \ r \ 0 \ x0B' – 2015-02-09 22:00:03

+0

我喜歡明確,尤其是對於例子。回答,但是,表明它是可選的。 – SuperJer 2015-02-09 22:04:28

0

如果strcmp返回-1是由於$ passW小於$ testPW http://php.net/manual/en/function.strcmp.php。如果$ user具有字符串「user#test // user = username test = password」,並且您使$ user_details = explode('#',$ user); $ user_details = explode('#',$ user); $ user_details =你有user_details [1];字符串「test // user = username test = password」;

+0

解決了你的問題? – 2015-02-12 03:54:47