Search code examples
phpstrcmp

PHP's strcmp function giving weird outputs?


I have a file called users.txt, where I have lots of lines of username and password combinations. Here's an example of this file:

kyle:pass1
steve:pass2
john:pass3
ralph:pass4

So a username would be steve and the password would be pass1. These are passed to my file, login.php, via POST. So here's what I've written so far:

$username = $_POST["name"];
$password = $_POST["password"];

$lines = file("users.txt");
foreach($lines as $line) {
    $inputUserInfo = explode(":", $line);
    $inputUsername = $inputUserInfo[0];
    $inputPassword = $inputUserInfo[1];
    if (strcmp($username, $inputUsername) == 0) {
        echo 'username matched!';
    }
    if (strcmp($password, $inputPassword) == 0) {
        echo 'password matched!';
    }
}

I'm not sure what's happening, but the username matches fine as the method strcmp returns 0. Then, when I try to match the password for steve and pass2, or any other theoretically valid combination, the method strcmp returns -2, -1, or anything other than zero.

I really can't tell why this is happening, I've tried everything I can think of. Can anybody tell what's going on here?


Solution

  • Don't forget to add the flags inside your file():

    $lines = file("users.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    

    This basically adds that newline in your password field. If you examine this carefully, your password has some added newline into it:

    var_dump($inputPassword);
    

    string(7) "pass2 
            " 
    

    Thus the mismatch.