Sophie Mackeral
Sophie Mackeral

Reputation: 917

How to get the similarity between two strings?

I want to create a function which will alert a user if there is a multiple brute force attempt on an account. The function will alert the user if there is more than 75% string match. I have performed this:

function Password_Match ($String, $Stored_Password){
    $New_String = str_split($String);
    $New_Stored_Password = str_split($Stored_Password);
        $Match = 0;
    foreach ($New_String AS $Value){
        if (in_array($Value,$New_Stored_Password)){
            $Match++;
        }
    }
    return $Match;

}

$String = "Test";
$Pass = "Tesst";
echo Password_Match($String,$Pass);

This returns 4, but there is obviously a flaw within my code that I can't figure out a solution. Assitance would be brilliant.

Upvotes: 1

Views: 95

Answers (3)

Daryl Gill
Daryl Gill

Reputation: 5524

Passwords should be encrypted using a one way encryption, they should not be stored in the database as plain text. BUT if you really want to approach this way.. Try something like this:

function Password_Match ($String, $Stored_Password){
    similar_text($String,$Stored_Password,$Percentage);
    if ($Percentage > 75){
        return true;
    }
    return false;
}

Upvotes: 0

Pekka
Pekka

Reputation: 449475

You shouldn't be doing this in the first place.

Brute force attacks should simply be prevented by imposing hourly / daily limits on failed attempts. What does the user care how close the hackers were to guessing the password?

Also, much more importantly, you shouldn't be storing the user's password in clear text in the first place. That's a far more serious security problem than you can make up by telling the user about cracking attempts.

See these questions for some in-depth discussion on how to properly store passwords:

Upvotes: 6

DevZer0
DevZer0

Reputation: 13535

What your trying to do is measure edit distance between two strings. PHP has a built in function to accomplish this.

int levenshtein ( string $str1 , string $str2 )

to wrap up the answer

$x = levenshtein ($str1 ,$str2);

$ratio = $x / strlen($str1); //or 2 

if ($ratio > 0.75) { //case match } 
else { //case miss match}

Upvotes: 1

Related Questions