Se vogliamo impedire che gli utenti del nostro sito usino password deboli dobbiamo necessariamente implementare un misuratore di robustezza delle password con PHP.

Una possibile soluzione potrebbe essere la seguente:


function check_password_strength( $password ) {
    if ( strlen( $password ) === 0 ) {
        return 0; // Stringa vuota
    }

    $strength = 0;

    $length = strlen( $password );

    
    if( strtolower( $password ) === $password || strtoupper( $password ) === $password ) {
        $strength += 1; // Solo caratteri minuscoli o maiuscoli
    }

    
    if( $length >= 8 && $length <= 15 ) {
        $strength += 1; // Lunghezza fino a 15 caratteri
    }

    
    if( $length >= 16 && $length <= 35 ) {
        $strength += 2; // Lunghezza fino a 35 caratteri
    }

    
    if( $length > 35 ) {
        $strength += 3; // Lunghezza maggiore di 35 caratteri
    }
    
    
    preg_match_all( '/[0-9]/', $password, $numbers );
    $strength += count( $numbers[0]); // Presenza di lettere e numeri

    
    preg_match_all( '/[|!@#$%&*\/=?,;.:\-_+~^\\g]/', $password, $specialchars );
    $strength += count( $specialchars[0] ); // Presenza di caratteri speciali

   
    $chars = str_split( $password );
    $num_unique_chars = count( array_unique( $chars ) );
    $strength += $num_unique_chars * 2; // Presenza di caratteri unici

    $strength = $strength > 99 ? 99 : $strength;
    $strength = floor( $strength / 10 + 1 );

    return $strength;
}

La funzione restituisce un valore compreso tra 1 e 10 dove 1 รจ il valore minimo e 10 il valore massimo.