首頁 > 後端開發 > php教程 > php 密碼強度檢測程式碼

php 密碼強度檢測程式碼

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
發布: 2016-07-25 08:56:56
原創
2284 人瀏覽過
本文介绍下,用php实现的用于检测密码强度的一段代码,有需要的朋友参考下。

在php编程中,尤其是用户注册这样的模块时,对用户密码强度的要求,再多也不过。

现在很多网站,都会对密码强度进行检测,以获取符合安全要求的用户密码。 不过,有些对密码强度检测的功能,是建立在js或其它脚本上的,这可能会被恶意破坏者越过密码检测,而进行破坏。

本文介绍的这段代码,基于对长度、特殊字符、数字、字母等进行检测,另外,还可以自己添加一些额外的字符,以加强密码的安全性。

看代码吧,如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

<?php

/**

 *

 * @检测密码强度

 * @param string $password

 * @return int

 * @edit bbs.it-home.org

 */

function testPassword($password)

{

    if ( strlen( $password ) == 0 )

    {

        return 1;

    }

 

    $strength = 0;

 

    /*** get the length of the password ***/

    $length = strlen($password);

 

    /*** check if password is not all lower case ***/

    if(strtolower($password) != $password)

    {

        $strength += 1;

    }

     

    /*** check if password is not all upper case ***/

    if(strtoupper($password) == $password)

    {

        $strength += 1;

    }

 

    /*** check string length is 8 -15 chars ***/

    if($length >= 8 && $length <= 15)

    {

        $strength += 1;

    }

 

    /*** check if lenth is 16 - 35 chars ***/

    if($length >= 16 && $length <=35)

    {

        $strength += 2;

    }

 

    /*** check if length greater than 35 chars ***/

    if($length > 35)

    {

        $strength += 3;

    }

     

    /*** get the numbers in the password ***/

    preg_match_all('/[0-9]/', $password, $numbers);

    $strength += count($numbers[0]);

 

    /*** check for special chars ***/

    preg_match_all('/[|!@#$%&*\/=?,;.:\-_+~^\\\]/', $password, $specialchars);

    $strength += sizeof($specialchars[0]);

 

    /*** get the number of unique chars ***/

    $chars = str_split($password);

    $num_unique_chars = sizeof( array_unique($chars) );

    $strength += $num_unique_chars * 2;

 

    /*** strength is a number 1-10; ***/

    $strength = $strength > 99 ? 99 : $strength;

    $strength = floor($strength / 10 + 1);

 

    return $strength;

}

 

/*** 调用示例 ***/

$password = 'php_tutorials_and_examples!123';

echo testPassword($password);

 

?>

登入後複製


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板