【问题标题】:php comparing two password stringsphp比较两个密码字符串
【发布时间】:2015-02-09 21:33:16
【问题描述】:

我正在使用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));
}

【问题讨论】:

  • 您永远不应该比较明文密码。 php.net/manual/en/faq.passwords.php
  • 您使用 printf 语句在一行上打印所有内容,但它在两行上输出。这告诉我$testPW 以换行符结尾
  • 尝试使用$tesPW = trim(user_details[1]);
  • @Devin_Kinh 你有预付款吗?
  • @Devin_Kinh 你解决了你的问题?不要忘记检查一个答案是否正确。

标签: php explode strcmp


【解决方案1】:

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

如果用户/密码匹配文件中的一行,此函数将返回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 "这个可选参数,默认参数就足够了。

【讨论】:

  • 您可以跳过\r\n\t 部分,因为默认情况下修剪会删除它们,实际上列表是" \t\n\r\0\x0B
  • 我喜欢直截了当,尤其是示例。不过,我会更新答案,说明它是可选的。
  • 从不在密码、用户名等方面使用== 的字符串松散比较。在PHP 中,"password"==0 为真,因此AuthenticateUser(0, 0) 为真,@987654331对于现有用户test,@ 将是 true,无论密码是什么。相反,至少使用与=== 的严格比较。更好的是,考虑password_verify()
  • @ChristopherK。你说的对。在这种情况下,被比较的两个项目都可能是来自 UI 中的文本文件和文本字段的字符串,因此类型比较并不是绝对必要的,但是看到这一点并根据他们的目的调整它的人可能不知道这一点。
【解决方案2】:

如果 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[1];字符串 "test //user= username test= password";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    相关资源
    最近更新 更多