实现图片验证码类 PHP
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现图片验证码类 PHP相关的知识,希望对你有一定的参考价值。
封装一个图片验证码类
<?php class Captcha{ private $img; private $imgX; private $imgY; private $codeNum; private $code; private $str="abcdefghjklmnpqrstuvwxyz123456789ABCDEFGHJKLMNPQRSTUVWXYZ"; public function __construct($imgX=80,$imgY=40,$codeNum=4){ $this->imgX=$imgX; $this->imgY=$imgY; $this->codeNum=$codeNum; } public function printImg(){ $this->createBg(); $this->getCode(); $this->setCode(); $this->setDot(); $this->setCurve(); $this->outImg(); } //创建画布背景图片 private function createBg(){ //创建画布 $this->img=imagecreate($this->imgX,$this->imgY); //给图片背景颜色分配 imagecolorallocate($this->img,243,251,254); } //输出背景图片 private function outImg(){ header("Content-type:image/jpeg"); imagejpeg($this->img); } //生成验证码 private function getCode(){ //生成验证码 for($i=0;$i<$this->codeNum;$i++){ $key=rand(0,strlen($this->str)-1); $this->code.=$this->str[$key]; } $this->setSession(); } //生成背景图片和文字颜色 private function setCode(){ for($i=0;$i<$this->codeNum;$i++){ $char_color=imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255)); $font_size=rand(3,5); $font_height=imagefontheight($font_size);//根据设置的字体大小获取字体高度 $x=($this->imgX/$this->codeNum)*$i;//设置验证码每个字的坐标位置 $y=rand(0,$this->imgY-$font_height-3); imagechar($this->img,$font_size,$x,$y,$this->code{$i},$char_color);//把字符串写到图片上 imagechar() } } //画干扰点 private function setDot(){ for($i=0;$i<=50;$i++){ $dot_color=imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255)); imagesetpixel($this->img,rand(1,80),rand(1,40),$dot_color);//把干扰点写到图片上 imagesetpixel() } } //画干扰线 private function setCurve(){ for($i=0;$i<=3;$i++){ $line_color=imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255)); imagearc($this->img,rand(1,$this->imgX),rand(1,$this->imgY),100,80,30,15,$line_color); } } //把验证码存储到session private function setSession(){ session_start(); $_SESSION[‘code‘]=strtolower($this->code); } } $captcha=new Captcha; $captcha->printImg();
在外部调用类
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> new document </title> <meta name="generator" content="editplus" /> <meta name="author" content="" /> <meta name="keywords" content="" /> <meta name="description" content="" /> <meta charset="utf-8"> </head> <body> <label>请输入验证码:</label><input type="text"><img src="captcha.php" onclick="this.src=‘captcha.php?‘+Math.random()" /> </body> </html>
以上是关于实现图片验证码类 PHP的主要内容,如果未能解决你的问题,请参考以下文章