1、实现效果生成验证验证码
2、验证码类CaptchaBase.php
<?php
class CaptchaBase
{
private $width;
private $height;
private $length;
public function __construct($width, $height, $length)
{
$this->width = $width;
$this->height = $height;
$this->length = $length;
}
public function generate()
{
$image = imagecreatetruecolor($this->width, $this->height);
$background_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $background_color);
$text_color = imagecolorallocate($image, 0, 0, 0);
$captcha_string = $this->generateRandomString($this->length);
$_SESSION['captcha'] = $captcha_string;
imagestring($image, 5, 5, 5, $captcha_string, $text_color);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
}
private function generateRandomString($length)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_string = '';
for ($i = 0; $i < $length; $i++) {
$random_string .= $characters[rand(0, strlen($characters) - 1)]." ";
}
return trim($random_string);
}
public function validate($input)
{
$captcha= strtolower(preg_replace('/\s+/', '', $_SESSION['captcha']));
$input= strtolower(preg_replace('/\s+/', '', $input));
if ($captcha&& $captcha ==$input) { // 将用户输入和保存的验证码都转换为小写形式进行比较
return true;
}
return false;
}
}
3、封装function.php
function Code(){
return new CaptchaBase(80, 30, 4);
}
4、使用和验证indexCrl.php
<?php
class indexCrl{
//生成验证码
public function index(){
echo Code()->generate();
}
//验证验证码
public function validate(){
if(Code()->validate($_GET['code'])){
echo '验证成功';
}else{
echo '验证失败';
}
}
}