Home Backend Development PHP Tutorial Generate intricate (tilted, sinusoidal, pasted, rotated) verification codes

Generate intricate (tilted, sinusoidal, pasted, rotated) verification codes

Mar 24, 2018 pm 05:52 PM
interference

This time I will bring you the method of generating intricate (inclined, sinusoidal interference lines, pasting, rotation verification) verification codes, and generating intricate (tilt, sinusoidal interference lines, pasting, rotation verification) verification codes What are the precautions? The following is a practical case, let’s take a look.

Verification code used by many websites now is very easy to be automatically recognized by software. This article introduces a PHP-generated complex verification code that adds effects such as tilting, string interference lines, pasting, and rotation.

There are three common verification code methods that are not easily recognized by software:

1. Font variation (generally distorted through algorithms)

2. Paste fonts (the QQ verification code is represented here, it is still difficult to find online, crack the QQ verification code)

3 , interference lines, noise (this kind of identification is quite easy and can be automatically identified by the program)

As mentioned above, the first and second methods are more difficult to identify.

Specific implementation code:

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

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

<?php

/**

 *带文字旋转,倾斜,黏贴,加正弦干扰线验证码*

 */

class Utils_Caption

{

    var $Width   = 60;      //图片宽

    var $Height   = 30;      //图片高

    var $Length   = 4;      //验证码位数

    var $BgColor  = "#FFFFFF"//背景色

    var $TFonts = array("font.ttf");

    var $TFontSize=array(17,20); //字体大小范围

    var $TFontAngle=array(-20,20); //旋转角度

    var $Chars  = "0123456789";     //验证码范围(字母数字)

    var $Code  = array();       //验证码

    var $Image  = "";       //图形对象

    var $FontColors=array(&#39;#f36161&#39;,&#39;#6bc146&#39;,&#39;#5368bd&#39;); //字体颜色,红绿蓝

    var $TPadden = 0.75;///字符间距,多少个字符

    var $Txbase = 5;///x轴两边距离

    var $Tybase =5 ;///y轴两边距离

    var $TLine =true; ///画干扰线

    public function RandRSI() ///生成验证码

    {

        $this->TFontAngle=range($this->TFontAngle[0],$this->TFontAngle[1]);

        $this->TFontSize=range($this->TFontSize[0],$this->TFontSize[1]);

        $arr=array();

        $Chars=$this->Chars;

        $TFontAngle=$this->TFontAngle;

        $TFontSize=$this->TFontSize;

        $FontColors=$this->FontColors;

        $code="";

        $font=dirname(FILE)."/font/".$this->TFonts[0];

        $charlen=strlen($Chars)-1;

        $anglelen=count($TFontAngle)-1; // 角度范围

        $fontsizelen=count($TFontSize)-1; // 角度范围

        $fontcolorlen=count($FontColors)-1; // 角度范围

        for($i=0;$i<$this->Length;$i++) ///得到字符与颜色

        {

            $char=$Chars[rand(0,$charlen)]; ///得到字符

            $angle=$TFontAngle[rand(0,$anglelen)]; ///旋转角度

            $fontsize=$TFontSize[rand(0,$fontsizelen)]; ///字体大小

            $fontcolor=$FontColors[rand(0,$fontcolorlen)]; ///字体大小

            $bound=$this->_calculateTextBox($fontsize,$angle,$font,$char); ///得到范围

            $arr[]=array($fontsize,$angle,$fontcolor,$char,$font,$bound); ///得到矩形框

            $code.=$char;

        }

        $this->Code=$arr//验证码

        return $code;

    }

    public function Draw() ///画图

    {

        if(empty($this->Code)) $this->RandRSI();

        $codes=$this->Code; ///用户验证码

        $wh=$this->_getImageWH($codes);

        $width=$wh[0];

        $height=$wh[1]; ///高度

        $this->Width=$width;

        $this->Height=$height;

        $this->Image = imageCreate( $width$height );

        $image=$this->Image;

        $back $this->_getColor2($this->_getColor( $this->BgColor)); ///背景颜色

        imageFilledRectangle($image, 0, 0, $width$height$back); ///填充背景

        $TPadden=$this->TPadden;

        $basex=$this->Txbase;

        $color=null;

        foreach ($codes as $v///逐个画字符

        {

            $bound=$v[5];

            $color=$this->_getColor2($this->_getColor($v[2]));

            imagettftext($image$v[0], $v[1], $basex$bound['height'],$color $v[4], $v[3]);

            $basex=$basex+$bound['width']*$TPadden-$bound['left'];///计算下一个左边距

        }

        $this->TLine?$this->_wirteSinLine($color,$basex):null; ///画干扰线

        header("Content-type: image/png");

        imagepng( $image);

        imagedestroy($image);

    }

    /**

     *通过字体角度得到字体矩形宽度*

     *

     * @param int $font_size 字体尺寸

     * @param float $font_angle 旋转角度

     * @param string $font_file 字体文件路径

     * @param string $text 写入字符

     * @return array 返回长宽高

     */

    private function _calculateTextBox($font_size$font_angle$font_file$text) {

        $box = imagettfbbox($font_size$font_angle$font_file$text);

        $min_x = min(array($box[0], $box[2], $box[4], $box[6]));

        $max_x = max(array($box[0], $box[2], $box[4], $box[6]));

        $min_y = min(array($box[1], $box[3], $box[5], $box[7]));

        $max_y = max(array($box[1], $box[3], $box[5], $box[7]));

        return array(

        'left' => ($min_x >= -1) ? -abs($min_x + 1) : abs($min_x + 2),

        'top' => abs($min_y),

        'width' => $max_x $min_x,

        'height' => $max_y $min_y,

        'box' => $box

        );

    }

    private function _getColor( $color //#ffffff

    {

        return array(hexdec($color[1].$color[2]),hexdec($color[3].$color[4]),hexdec($color[5].$color[6]));

    }

    private function _getColor2( $color //#ffffff

    {

        return imagecolorallocate ($this->Image, $color[0], $color[1], $color[2]);

    }

    private function _getImageWH($data)

    {

        $TPadden=$this->TPadden;

        $w=$this->Txbase;

        $h=0;

        foreach ($data as $v)

        {

            $w=$w+$v[5]['width']*$TPadden-$v[5]['left'];

            $h=$h>$v[5]['height']?$h:$v[5]['height'];

        }

        return array(max($w,$this->Width),max($h,$this->Height));

    }

    //画正弦干扰线

    private function _wirteSinLine($color,$w)

    {

        $img=$this->Image;

        $h=$this->Height;

        $h1=rand(-5,5);

        $h2=rand(-1,1);

        $w2=rand(10,15);

        $h3=rand(4,6);

        for($i=-$w/2;$i<$w/2;$i=$i+0.1)

        {

            $y=$h/$h3*sin($i/$w2)+$h/2+$h1;

            imagesetpixel($img,$i+$w/2,$y,$color);

            $h2!=0?imagesetpixel($img,$i+$w/2,$y+$h2,$color):null;

        }

    }

}

Copy after login

DEMO code:

1

2

3

4

5

6

7

8

$rsi = new Utils_Caption();

$rsi->TFontSize=array(15,17);

$rsi->Width=50;

$rsi->Height=25;

$code $rsi->RandRSI();

session_start();

$_SESSION["CHECKCODE"] = $code;

$rsi->Draw();

Copy after login

Running effect:

Everyone can Modify the corresponding values ​​in the code to achieve the complexity you need

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

php retains key value + merged array detailed explanation

How to remove duplicates in a two-dimensional array value

The above is the detailed content of Generate intricate (tilted, sinusoidal, pasted, rotated) verification codes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles