PHP字符串比较难度

时间:2010-12-11 21:44:21

标签: php file-io

我正在尝试用PHP编程任务帮助一个朋友。他需要从文件中读取密码和用户名,并将它们与从表单输入的用户名($ user)和密码($ password)进行比较,以验证用户身份。 (简单,没有任何安全性,只是学术上的)

问题是字符串的比较。我在使用==,===和strcmp之间来回走动,但似乎没有任何工作正常。任何想法?

这是正在阅读的文本文件:

UserData.txt

test:pass
testa:pass2
testb:pass4
testc:pass6

<?php

$fh = fopen("UserData.txt", "r") or die("Can't open file");

$line = "";
$line_length = 0;
$div = 0;
$accounts = array();

while($line = fgets($fh)) {
    $div = strpos($line, ":"); //positing of ":" dividing username and password
    $line_length = strlen($line); //Total length of username + : + password line entry

    $accounts[substr($line, 0, $div)] = substr($line, $div + 1, $line_length);
}

foreach ($accounts as $key => $value) {
    if(($user === $key) && ($password === $value)) {
        echo "MATCH - user/pass correct<br/>";
        //Just needs to echo the above line if user/pass correct
    }
}

?>

HTML文件:

<form name="myform" method="GET" action="login.php">
Please Login to order
User Name:
<input type="text" name="user" value="" size="10"/>
Password:
<input type="password" name="password" value="" size="10"/>
<input type="submit" name="submit" value="Log In" >

更新了login.php文件:

<?php

$lines = file('UserData.txt', FILE_IGNORE_NEW_LINES);
foreach ($lines as $line)
{
  $arr = explode(':', $line);
  if ($arr[0]==$user && $arr[1]==$password)
  {
     echo "MATCH - user/pass correct<br/>";
  } else {
     echo "NO<br />";
  }
}

echo "<br />";
var_dump($user);
echo "<br />";
var_dump($password);
echo "<br />";
echo phpversion();
?>

输出:

NO
NO
NO
NO

string(4) "test" 
string(4) "pass" 
4.4.9

4 个答案:

答案 0 :(得分:2)

简短:

$lines = file('UserData.txt', FILE_IGNORE_NEW_LINES);
foreach ($lines as $line)
{
  $arr = explode(':', $line);
  if ($arr[0]==$user && $arr[1]==$password)
  {
     echo "MATCH - user/pass correct<br/>";
  }
}

如果文件UserData.txt很大,请增加内存以处理

答案 1 :(得分:1)

fgets会读取最终换行符,因此"test"的密码为"pass\n"。下次遇到类似这样的问题时,在比较字符串上使用var_dump并仔细检查输出。

无论哪种方式,请考虑一下:

$accounts = array();
foreach (file("UserData.txt",FILE_IGNORE_NEW_LINES) as $line) {
  list($user,$pass) = explode(':',$line);
  $accounts[$user] = $pass;
}

if ($accounts[$the_user] === $the_password) { /* Password is correct */ }

答案 2 :(得分:1)

看起来像是一个错误。

尝试:

while($line = fgets($fh)) { // or better, use file()
    list($u, $p) = explode(':', $line, 2);
    $accounts[$u] = $p;
}

答案 3 :(得分:0)

首先,您宁愿将整个文件读入数组:

$file = file('userdata.txt') or die("Can't open file");

之后,您可以使用explode()拆分每一行,并将用户和密码添加到帐户数组中:

foreach($file as $line){
    $up = explode(':', $line);
    // here you can also check line validity
    if(count($up)!=2){
        continue; // skip it
    }
    $accounts[ trim($up[0]) ] = trim($up[1]);
}

现在很简单:

if(isset($accounts[$user]) && $accounts[$user]===$password){
    echo "Welcome, $user"; // this should be sanitized before use
}
else{
    echo "Wrong username or password";
}