-
Notifications
You must be signed in to change notification settings - Fork 8
/
Captcha.php
122 lines (103 loc) · 2.99 KB
/
Captcha.php
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
<?php
/**
* Copyright (c) 2019. PHP-QuickORM Captcha
* Author: Rytia Leung
* Email: Rytia@Outlook.com
* Github: github.com/php-quickorm/captcha
*/
class Captcha
{
private $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZaabcdefghijklmnopqrstuvwxyz1234567890";
private $font;
private $imageResource;
private $level;
private $code;
private $caseSensitive;
/**
* Captcha constructor.
* @param int $level
* @param boolean $caseSensitive
*/
public function __construct($level = 2, $caseSensitive = false)
{
$this->level = $level;
$this->caseSensitive = $caseSensitive;
// load the TrueType font
$this->font = __DIR__.'/arial.ttf';
// create image
$this->imageResource = imagecreate(200, 77);
imagecolorallocate($this->imageResource, 255, 255, 255);
// generate
$this->generate();
// add lines
if ($this->level == 3) {
$this->addLines();
}
}
/**
* @return resource
*/
public function getImageResource()
{
return $this->imageResource;
}
/**
* @return string
*/
public function getCode()
{
return $this->code;
}
/**
* send http response with the captcha image
*/
public function render()
{
header('Content-Type: image/png');
imagepng($this->imageResource);
imagedestroy($this->imageResource);
}
/**
* generate the code and image
*/
private function generate()
{
$output = '';
$length = strlen($this->str);
for ($i = 1; $i < 5; $i++) {
// get random char
$char = $this->str[rand(0, $length - 1)];
$output .= $char;
// get font size
$fontSize = ($this->level > 1) ? rand(20, 48) : 28;
imagettftext($this->imageResource, $fontSize, rand(-35, 35), 35 * $i, 55, imagecolorallocate($this->imageResource, rand(0, 240), rand(0, 240), rand(0, 240)), $this->font, $char);
}
$this->code = ($this->caseSensitive) ? $output : strtolower($output);
}
/**
* @param $str
* @return bool
* check the code
*/
public function check($str){
if (!$this->caseSensitive){
return strtolower($str) == strtolower($this->code);
}
else{
return $str == $this->code;
}
}
/**
* add line to image if level > 2
*/
private function addLines()
{
$lines = rand(1, 3);
for ($i = 0; $i < $lines; $i++) {
imageline($this->imageResource, rand(0, 200), rand(0, -77), rand(0, 200), rand(77, 144), imagecolorallocate($this->imageResource, rand(0, 240), rand(0, 240), rand(0, 240)));
}
for ($i = 0; $i < 5 - $lines; $i++) {
imageline($this->imageResource, rand(0, -200), rand(0, 77), rand(200, 400), rand(0, 77), imagecolorallocate($this->imageResource, rand(0, 240), rand(0, 240), rand(0, 240)));
}
}
}