<?php
class
Captcha{
private
$width
;
private
$height
;
private
$fontsize
;
private
$pixes
;
private
$lines
;
private
$str_len
;
public
function
__construct(
$arr
=
array
()){
$this
->width = isset(
$arr
['width']) ?
$arr
['width'] :
$GLOBALS
['config']['captcha']['width'];
$this
->height = isset(
$arr
['height']) ?
$arr
['height'] :
$GLOBALS
['config']['captcha']['height'];
$this
->fontsize = isset(
$arr
['fontsize']) ?
$arr
['fontsize'] :
$GLOBALS
['config']['captcha']['fontsize'];
$this
->pixes = isset(
$arr
['pixes']) ?
$arr
['pixes'] :
$GLOBALS
['config']['captcha']['pixes'];
$this
->lines = isset(
$arr
['lines']) ?
$arr
['lines'] :
$GLOBALS
['config']['captcha']['lines'];
$this
->str_len = isset(
$arr
['str_len']) ?
$arr
['str_len'] :
$GLOBALS
['config']['captcha']['str_len'];
}
public
function
generate(){
$img
= imagecreatetruecolor(
$this
->width,
$this
->height);
$bg_color
= imagecolorallocate(
$img
,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
imagefill(
$img
,0,0,
$bg_color
);
$this
->getLines(
$img
);
$this
->getPixels(
$img
);
$captcha
=
$this
->getCaptcha();
$str_color
= imagecolorallocate(
$img
,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
$start_x
=
ceil
(
$this
->width/2) - 25;
$start_y
=
ceil
(
$this
->height/2) - 8;
if
(imagestring(
$img
,
$this
->fontsize,
$start_x
,
$start_y
,
$captcha
,
$str_color
)){
header('Content-type:image/png');
imagepng(
$img
);
}
else
{
return
false;
}
}
private
function
getCaptcha(){
$str
= implode('',
array_merge
(range('a','z'),range('A','Z'),range(1,9)));
$captcha
= '';
for
(
$i
= 0,
$len
=
strlen
(
$str
);
$i
<
$this
->str_len;
$i
++){
$captcha
.=
$str
[mt_rand(0,
$len
- 1)] . ' ';
}
$_SESSION
['captcha'] =
str_replace
(' ','',
$captcha
);
return
$captcha
;
}
private
function
getPixels(
$img
){
for
(
$i
= 0;
$i
<
$this
->pixes;
$i
++){
$pixel_color
= imagecolorallocate(
$img
,mt_rand(100,150),mt_rand(100,150),mt_rand(100,150));
imagesetpixel(
$img
,mt_rand(0,
$this
->width),mt_rand(0,
$this
->height),
$pixel_color
);
}
}
private
function
getLines(
$img
){
for
(
$i
= 0;
$i
<
$this
->lines;
$i
++){
$line_color
= imagecolorallocate(
$img
,mt_rand(150,200),mt_rand(150,200),mt_rand(150,200));
imageline(
$img
,mt_rand(0,
$this
->width),mt_rand(0,
$this
->height),mt_rand(0,
$this
->width),mt_rand(0,
$this
->height),
$line_color
);
}
}
public
static
function
checkCaptcha(
$captcha
){
return
(
strtolower
(
$captcha
) ===
strtolower
(
$_SESSION
['captcha']));
}
}