Search code examples
phppasswordsstrcmp

PHP: strcmp does not work?


I was trying to read passwords from a textfile, and compare it to the password the user entered. But although it appears to me that both word are exactly the same, my script says something else:

$user = $_POST['user'];
$pass = $_POST['pass']; //HTML form element with type="password"

$line;
$retrievedPassword = "";

$f = fopen("data/abc.log", "r");

// Read line by line until end of file
while(!feof($f)) { 
    $line = fgets($f);
    if (startsWith($line, $user)) {
      break; //password found
    }
}

fclose($f);

$var = explode(":", $line);
$retrievedPassword = $var[1];

echo $pass." ".$retrievedPassword; // example: password password

if (strcmp($pass, $var[1]) == 0) {
    header('Location: user.php'); //never the case
}else {
    //header('Location: index.php');
}


function startsWith($haystack, $needle)
{
    return !strncmp($haystack, $needle, strlen($needle));
}

Is the password encrypted or something like that or why does this code not work?


Solution

  • When reading from a file, always assume 'mess' to be in there. Especially text files often have different line separators depending on which program on which OS was used to edit them - historically Windows uses CRLF, Mac CR and *nix variants LF, but modern editors like Notepad2 and Notepad++ allow you to configure them.

    Before exploding the line on the colon separator, use trim() to remove any extraneous whitespace like obsolete line separators and trailing spaces/tabs.

    As a side note on debugging: remember that you are outputting HTML to a browser, which silently collapses all whitespace. To look for reasons why 2 strings are not identical, wrap the echo statement in apostrophes (echo "'$sample1' '$sample2'";), or use var_dump as suggested by Rocket Hazmat, or output it in a <pre> section. Also, if the strings look identical in output, doublecheck with strlen to know there's no 'mess' in there.