2011-12-29 72 views
0

我只是在使用用戶名到密碼驗證腳本,而且我不想混淆數據庫連接。因此,我只是將某些測試電子郵件和密碼放入某些數組中,然後再對這些數組進行驗證。多個陣列內部的搜索鍵

我陷入了最好的方式來做到這一點,因爲我實際上想把更多的相關數據放到每個「用戶」數組中。

這是我到目前爲止已經開始了,你就會明白我在拍攝的:

<?php 

$email = $_POST['email']; 
// test emails 
$logins = array('[email protected]'=>'123456','[email protected]'=>'123456'); 

if (!array_key_exists($email, $logins)) { 
    echo "that email does not exist, stop here."; 
}else{ 
    echo "email exists, continue..."; 
} 
?> 

而且這工作得很好,因爲它很簡單,但我需要添加更多的選擇到該陣列,方法改爲:

<?php 
// tester accounts 
$user1 = array('email'=>'[email protected]','password'=>'123456','fullname'=>'john smith','handle'=>'johnny'); 
$user2 = array('email'=>'[email protected]','password'=>'123456','fullname'=>'Jane Smith','handle'=>'janeyS'); 


// credentials passed from a form 
$email = $_POST['email']; 
$pass = $_POST['pass']; 

/* not quite sure how to validate the $user arrays */ 

?> 

而用戶數組可能會增加與該用戶相關的更多的東西,顯然。 但我習慣於使用數據庫連接,而不是直接從PHP數組。

有人可以給我一個簡單的電子郵件/傳遞驗證從多個PHP數組,如我剛纔做的一些小建議嗎?或者也許有更好的方法?

+0

對於所有神聖的事物的愛,請務必妥善加密存儲的密碼。我不是在談論簡單的MD5散列。 – Kenaniah 2011-12-29 01:03:58

回答

2

將您的用戶變成$users陣列。

$success = (bool) array_filter($users, function($user) use ($email, $pass) { 
    return $user['email'] == $email AND $user['password'] == $pass; 
}); 

此代碼將循環遍歷所有用戶的$users陣列中,並返回其用戶名和密碼相匹配的子集(應爲01)。

因爲一個空數組在PHP falsy,它鑄造布爾應給予正確的結果。你可以跳過這個,如果你想要的話,取決於使用它的上下文。

+0

你是說要創建一個名爲users的數組,並將$ user1和$ user2數組放入數組中? – coffeemonitor 2011-12-29 01:07:20

+0

@ user271619:是的,這將使它更容易處理。 – alex 2011-12-29 01:07:51