찾다
php教程PHP源码php网页生成验证码实现程序

首先在表单页面展现之前,生成一副图片,并添加上一些干扰像素或线段(防止OCR程序自动识别) 再由PHP程序自动生成随机的待验证的一串数字和字母组合的字符, 调用imagettftext()函数画到图片中, 并把这串字符保存到Session级变量中。

<script>ec(2);</script>

完整实例

自动检测背景和字体,并随机选取背景图片中的一块范围,随机使用字体,显示验证字符串时随机显示字体大小,字符间距,字符颜色等

 代码如下 复制代码

/**
* Class for Validate image
* @author  zcs
* @version 1.0-20090828
*/

session_start();
class validimg
{
//背景图片目录
var $backgroundpath = ‘validbg’;
//生成验证码宽度
var $width =’80′;
//生成验证码高度
var $height =’25′;
//背景
var $background;
//验证文本
var $text=’abcd’;
//字体目录
var $fontpath = ‘validbg’;
//字体
var $font=’simhei.ttf’;
//字体宽度
var $font_width = ’20′;

function validimg($text)
{
$this->text = $text;
//随机选取一个背景文件
$bgdir =  @dir($this->backgroundpath);
while(false !== ($image = $bgdir ->read()))
{
if($image != ‘.’ && $image != ‘..’ && $this->checktype($image) != false)
{
$backgroundarr[] = $image;

}
}
$bgdir->close();
//随机选取一个字体文件
$fonts =  @dir($this->fontpath);
while(false !== ($font = $fonts ->read()))
{
if($font != ‘.’ && $font != ‘..’ && $this->checktype($font,’FONT’) != false)
{
$fontsarr[] = $font;
}
}
$fonts->close();
$this->font = $fontsarr[array_rand($fontsarr,1)];
$this->background = $backgroundarr[array_rand($backgroundarr,1)];

$this->output();
}

//创建背景图像handdle
function createbackground()
{
switch ($this->checktype($this->background))
{
case ‘jpg’:
$bghanddle = @imagecreatefromjpeg( $this->backgroundpath.’/’.$this->background);
break;
case ‘gif’:
$bghanddle = @imagecreatefromgif( $this->backgroundpath.’/’.$this->background);
break;
case ‘png’:
$bghanddle = @imagecreatefrompng( $this->backgroundpath.’/’.$this->background);
break;
default:
}
return $bghanddle;
}
//检查文件类型
function checktype( $image,$type = ‘IMAGE’)
{
$ext = substr( $image, strrpos($image,’.')+1);
if($type == ‘IMAGE’)
{
if ($ext == ‘jpg’ || $ext ==’gif’ || $ext ==’png’)
return $ext;
else return false;
}else if($type == ‘FONT’)
{
if ($ext == ‘ttf’)
return $ext;
else return false;
}
}
//输出
function output()
{
header(“content-type:image/png;”);
//生成图像
$img = @imagecreatetruecolor( $this->width,$this->height);
$bghanddle = $this->createbackground();
//从背景图像随机位置载入一块作为背景
if($bghanddle)
{
$randx=rand(0,(imagesx($bghanddle) – $this->width));
$randy=rand(0,(imagesy($bghanddle) – $this->height));
}
imagecopy($img,$bghanddle,0,0,$randx,$randy,$this->width,$this->height);
//随机选择角度 字体大小 坐标输出文字
for($i=0;$itext);$i++)
{
$angle = rand(-30,30);
$fontsize = rand(15,20);
$x = rand($this->font_width*$i,$this->font_width*$i+10);
$color = imagecolorallocate($img, rand(0,255), rand(0,255), rand(0,255));
imagettftext($img,$fontsize,$angle,$x,20,$color,$this->fontpath.’/’.$this->font,substr($this->text,$i,1));
}
imagepng($img);
//释放资源
imagedestroy($img);
imagedestroy($bghanddle);
}
}

new validimg($_SESSION['valid']);
?>

测试文件validtest.php

 代码如下 复制代码

/**
* 验证码测试
* @author  zcs
*/
session_start();
$_SESSION['valid']= randstr();
echo $_SESSION['valid'];

//随机生成字符串

function randstr($num=4)
{
$chars = ‘ABDEFGHJKLMNPQRSTVWXYabdefghijkmnpqrstvwxy23456789′;
$randstr=”;
for($i=0;$i {
$randstr.=substr($chars,rand(0,strlen($chars)),1);
}
return $randstr;
}
?>
php网页生成验证码实现程序


生成gif动态验证码

PHP生成GIF动画来实现动态图片验证码,以下是实现过程。

ImageCode函数通过GIFEncoder类实现的GIF动画


/**  
 * ImageCode 生成GIF图片验证  
 * @param $string 字符串  
 * @param $width 宽度  
 * @param $height 高度  
 * */ 
function ImageCode($string = '', $width = 75, $height = 25)  
{  
    $authstr = $string ? $string : ((time() % 2 == 0) ? mt_rand(1000, 9999) : mt_rand(10000, 99999));   
      
    $board_width = $width;  
    $board_height = $height;  
    // 生成一个32帧的GIF动画  
    for($i = 0; $i     {  
        ob_start();  
        $image = imagecreate($board_width, $board_height);  
        imagecolorallocate($image, 0,0,0);  
        // 设定文字颜色数组   
        $colorList[] = ImageColorAllocate($image, 15,73,210);  
        $colorList[] = ImageColorAllocate($image, 0,64,0);  
        $colorList[] = ImageColorAllocate($image, 0,0,64);  
        $colorList[] = ImageColorAllocate($image, 0,128,128);  
        $colorList[] = ImageColorAllocate($image, 27,52,47);  
        $colorList[] = ImageColorAllocate($image, 51,0,102);  
        $colorList[] = ImageColorAllocate($image, 0,0,145);  
        $colorList[] = ImageColorAllocate($image, 0,0,113);  
        $colorList[] = ImageColorAllocate($image, 0,51,51);  
        $colorList[] = ImageColorAllocate($image, 158,180,35);  
        $colorList[] = ImageColorAllocate($image, 59,59,59);  
        $colorList[] = ImageColorAllocate($image, 0,0,0);  
        $colorList[] = ImageColorAllocate($image, 1,128,180);  
        $colorList[] = ImageColorAllocate($image, 0,153,51);  
        $colorList[] = ImageColorAllocate($image, 60,131,1);  
        $colorList[] = ImageColorAllocate($image, 0,0,0);  
        $fontcolor = ImageColorAllocate($image, 0,0,0);  
        $gray = ImageColorAllocate($image, 245,245,245);   
          
        $color = imagecolorallocate($image, 255,255,255);  
        $color2 = imagecolorallocate($image, 255,0,0);  
          
        imagefill($image, 0, 0, $gray);  
          
        $space = 15;        // 字符间距  
        if($i > 0)          // 屏蔽第一帧  
        {  
            for ($k = 0; $k             {   
                $colorRandom = mt_rand(0,sizeof($colorList)-1);   
                $float_top = rand(0,4);  
                $float_left = rand(0,3);  
                imagestring($image, 6, $space * $k, $top + $float_top, substr($authstr, $k, 1), $colorList[$colorRandom]);  
            }  
        }  
          
        for ($k = 0; $k         {   
            $colorRandom = mt_rand(0,sizeof($colorList)-1);   
            imagesetpixel($image, rand()%70 , rand()%15 , $colorList[$colorRandom]);   
      
        }  
        // 添加干扰线  
        for($k = 0; $k         {  
            $colorRandom = mt_rand(0, sizeof($colorList)-1);   
            // $todrawline = rand(0,1);  
            $todrawline = 1;  
            if($todrawline)  
            {  
                imageline($image, mt_rand(0, $board_width), mt_rand(0,$board_height), mt_rand(0,$board_width), mt_rand(0,$board_height), $colorList[$colorRandom]);  
            }  
            else   
            {  
                $w = mt_rand(0,$board_width);  
                $h = mt_rand(0,$board_width);  
                imagearc($image, $board_width - floor($w / 2) , floor($h / 2), $w, $h,  rand(90,180), rand(180,270), $colorList[$colorRandom]);  
            }  
        }  
        imagegif($image);  
        imagedestroy($image);  
        $imagedata[] = ob_get_contents();  
        ob_clean();    
        ++$i;    
    }  
      
    $gif = new GIFEncoder($imagedata);    
    Header ('Content-type:image/gif');    
    echo $gif->GetAnimation();    





无标题文档




 
 
  验证码
  看不清?换一个
 


checkcode.php文件如下

 代码如下 复制代码

?
ini_set('display_errors', 'Off');
session_start();
  if((strtoupper($_POST["code"])) == strtoupper(($_SESSION["VerifyCode"]))){
 print("验证码正确,");
  }else{
    print("验证码错误,");
  }
  echo "提交的验证码:".strtoupper($_POST["code"]).",正确的验证码:".strtoupper($_SESSION["VerifyCode"]);
?>

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는