2012-12-12 85 views
0

答案編輯:PHP不區分大小寫usermame比賽

的修復是改變:
if (get_user_data($input_user, $logindata) === $input_pwd) {

if (get_user_data(strtolower($input_user), $logindata) === $input_pwd) {

,使用戶名被強制爲小寫。我只需要有意識地將我的用戶名全部保存爲小寫字母。我們知道strcasecmp。我不確定這將如何適用於我的工作代碼,因爲您只能比較2個變量。

我可以在下面的工作代碼的上下文中使preg_match不區分大小寫嗎? 我可以將/i正則表達式添加到我的preg_match命令中以返回變量嗎?

我只想讓用戶輸入的用戶名(包括域名)不區分大小寫。 (即[email protected]),而無需將有效用戶名的每個組合添加到我的僞數據庫!

這是我的工作代碼:

// Get users 
$input_pwd = (isset($_POST["password"]) ? $_POST["password"] : ''); 
$input_user = (isset($_POST["username"]) ? $_POST["username"] : ''); 

// Your pseudo database here 
$usernames = array(
"[email protected]", 
"[email protected]", 
"[email protected]", 
"[email protected]", 
"/[a-z][A-Z][0-9]@domain2\.com/", // use an emtpy password string for each of these 
"/[^@][email protected]\.com/"    // entries if they don't need to authenticate 
); 

$passwords = array("password1", "password2", "password3", "password4", "", ""); 

// Create an array of username literals or patterns and corresponding redirection targets 
$targets = array(
"[email protected]"   => "http://www.google.com", 
"[email protected]"   => "http://www.yahoo.com", 
"[email protected]"   => "http://www.stackoverflow.com", 
"[email protected]"   => "http://www.serverfault.com", 
"/[a-z][A-Z][0-9]@domain2\.com/" => "http://target-for-aA1-usertypes.com", 
"/[^@][email protected]\.com/"   => "http://target-for-all-domain3-users.com", 
"/.+/"       => "http://default-target-if-all-else-fails.com", 
); 

$logindata = array_combine($usernames, $passwords); 

if (get_user_data($input_user, $logindata) === $input_pwd) { 

    session_start(); 
    $_SESSION["username"] = $input_user; 
    header('Location: ' . get_user_data($input_user, $targets)); 
    exit; 

} else { 
// Supplied username is invalid, or the corresponding password doesn't match 
    header('Location: login.php?login_error=1'); 
    exit; 
} 

function get_user_data ($user, array $data) { 

    $retrieved = null; 

    foreach ($data as $user_pattern => $value) { 

     if (
       ($user_pattern[0] == '/' and preg_match($user_pattern, $user)) 
      or ($user_pattern[0] != '/' and $user_pattern === $user) 
     ) { 
      $retrieved = $value; 
      break; 
     } 
    } 
    return $retrieved; 
} 
+1

我不知道你的意思是「返回的變量」,但將我加入preg_match會使其不區分大小寫。 – RonaldBarzell

+0

你可以在代碼片段的上下文中添加你的回覆,我可以接受你的答案:) – James

+0

只是做了:)。我希望這段代碼足夠了。 – RonaldBarzell

回答

0

您可以在PHP中使用i進行不區分大小寫的匹配。例如,下面將打印'This matches!':

<?php 
if (preg_match('/def/i', 'ABCDEF')) { 
    echo 'This matches!'; 
} 
?> 

所以,只需將我添加到模式,並將案件將被忽略。

0

一種方法,如果你想不區分大小寫的用戶名是始終小寫一個新的,當你保存它,然後總是小寫比較值當你檢查。 (這比使用preg_match快很多。)

+0

這項工作? 'if(get_user_data(strtolower($ input_user),$ logindata)=== $ input_pwd){'到目前爲止似乎按預期工作? – James

+0

是的,這就是主意,儘管我會在'get_user_date()'內執行'strtolower()'。 – staticsan