php比较两个密码字符串


php comparing two password strings

我正在使用explode()将从文本文件读取的字符串转换为数组,用于与用户的输入进行比较。

文本文件包含:

 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));
}

假设这是一个简单的应用程序,适用于有限环境中的特定人群,我将避免评论与此方法相关的安全问题。

如果用户/通行证与文件中的一行匹配,此函数将返回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
}

您也可以使用不带可选参数"'r'n't "trim($line[0]),作为足够的默认参数。

如果strcmp return-1是由于$passW小于$testPWhttp://php.net/manual/en/function.strcmp.php.

如果$user有字符串"user#test//user=usernametest=password",并且您使$user_details=爆炸('#',$user);您有user_details[1];字符串"test//user=用户名test=密码";