Search code examples
phpexplodestrcmp

php comparing two password strings


I'm using explode() to convert a string read from a text file to an array, which I use to compare with input from a user.

The text file contains:

 user#test //user= username test= password

When I try to use strcmp() it returns -1 even though printing the two string variables results with an output of

test||test
=-1

which I print with:

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

Solution

  • Assuming this is a simple app for a select group of folks in a limited environment, I will avoid commenting on the security issues related to this method.

    This function will return true if the user/pass match a line in the file, false if not.

    //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
    }
    

    You may also use trim($line[0]) without the optional parameter of "\r\n\t ", as the default parameter sufficient.