PHP 확인 코드 클래스 ValidateCode

不言
풀어 주다: 2023-03-25 11:20:01
원래의
2446명이 탐색했습니다.

이 글은 주로 PHP 검증 코드 클래스 ValidateCode를 자세히 분석하는데, 관심 있는 친구들은 이를 참고할 수 있습니다.

PHP 파싱 검증 코드 클래스

1.Start

온라인에서 ValidateCode가 작성된 것을 보았습니다. 인증코드 클래스를 생성하는데는 PHP를 사용하는데, 느낌이 좋아서 분석하고 학습하는데 활용하겠습니다.

2. 클래스 다이어그램

3. 인증 코드 클래스의 일부 코드

3.1 변수 정의

  //随机因子
  private $charset = 'abcdefghjkmnprstuvwxyzABCDEFGJKMNPRSTUVWXYZ23456789';
  private $code;
  private $codeLen = 4;

  private $width = 130;
  private $heigh = 50;
  private $img;//图像

  private $font;//字体
  private $fontsize = 20;
로그인 후 복사

$charset은 임의의 요소입니다. 여기에는 쉽지 않습니다. 문자 "i,l,o,q" 및 숫자 "0,1"과 같은 문자입니다. 필요한 경우 중국어 또는 기타 문자나 계산 등을 추가할 수 있습니다.

$codeLen은 인증 코드의 길이를 나타내며 일반적으로 4자리입니다.

3.2 생성자, 확인 코드 글꼴 설정, 트루 컬러 이미지 생성 img

public function __construct()
  {
    $this->font = ROOT_PATH.'/font/Chowderhead.ttf';
    $this->img = imagecreatetruecolor($this->width, $this->heigh);
  }
로그인 후 복사

3.3 $code 확인 코드로 무작위 요소에서 4자를 무작위로 선택합니다.


//生成随机码
  private function createCode()
  {
    $_len = strlen($this->charset) - 1;
    for ($i = 0; $i < $this->codeLen; $i++) {
      $this->code .= $this->charset[mt_rand(0, $_len)];
    }
  }
로그인 후 복사

3.4 인증코드 배경색을 생성합니다.

//生成背景
  private function createBg()
  {
$color = imagecolorallocate($this->img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));
    imagefilledrectangle($this->img, 0, $this->heigh, $this->width, 0, $color);

  }
로그인 후 복사

그 중 mt_rand(157, 255)는 더 밝은 색상을 무작위로 선택하는 데 사용됩니다.

3.5 이미지에 텍스트를 생성합니다.

//生成文字
  private function createFont()
  {
    $_x = $this->width / $this->codeLen;
    $_y = $this->heigh / 2;
    for ($i = 0; $i < $this->codeLen; $i++) {
      $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
      imagettftext($this->img, $this->fontsize, mt_rand(-30, 30), $_x * $i + mt_rand(3, 5), $_y + mt_rand(2, 4), $color, $this->font, $this->code[$i]);
    }
  }
로그인 후 복사

이미지에 있는 텍스트의 위치와 각 텍스트의 색상을 주로 고려하여 이미지에 인증 코드 텍스트를 생성합니다.

n번째 텍스트의 x축 위치 제어 = (이미지 너비 / 인증 코드 길이) * (n-1) + 임의 오프셋 숫자, 여기서 n = {d1....n}

n번째 텍스트 제어 y -텍스트의 축 위치 = 이미지 높이 / 2 + 임의 오프셋 번호

mt_rand(0, 156)는 텍스트 색상을 무작위로 선택하고, 0-156은 더 어두운 색상을 선택하는 것을 목표로 합니다.

mt_rand(-30, 30) 임의 텍스트 회전.

3.6 이미지에 선과 눈송이 생성

//生成线条,雪花
  private function createLine()
  {
    for ($i = 0; $i < 15; $i++) {
      $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
      imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->heigh), mt_rand(0, $this->width), mt_rand(0, $this->heigh), $color);
    }
    for ($i = 0; $i < 150; $i++) {
      $color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
      imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->heigh), &#39;#&#39;, $color);
    }
  }
로그인 후 복사

선을 그릴 때는 더 어두운 색상 값을 선택하고, 눈송이를 그릴 때는 밝은 색상 값을 선택하세요. 사람의 눈에 최대한 영향을 주지 않도록 하는 것이 목적입니다. 인증코드를 식별하여 자동 인증코드 인식 메커니즘을 방해할 수 있습니다.

3.7 외부 통화를 위해 외부적으로 인증 코드 이미지를 생성합니다.

//对外生成
  public function doImg()
  {

    $this->createBg();   //1.创建验证码背景
    $this->createCode();  //2.生成随机码
    $this->createLine();  //3.生成线条和雪花
    $this->createFont();  //4.生成文字
    $this->outPut();    //5.输出验证码图像
  }
로그인 후 복사

3.8 전체 코드:

img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));
    imagefilledrectangle($this->img, 0, $this->heigh, $this->width, 0, $color);

  }

  //生成文字
  private function createFont()
  {
    $_x = $this->width / $this->codeLen;
    $_y = $this->heigh / 2;
    for ($i = 0; $i < $this->codeLen; $i++) {
      $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
      imagettftext($this->img, $this->fontsize, mt_rand(-30, 30), $_x * $i + mt_rand(3, 5), $_y + mt_rand(2, 4), $color, $this->font, $this->code[$i]);
    }
  }

  //生成线条,雪花
  private function createLine()
  {
    for ($i = 0; $i < 15; $i++) {
      $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
      imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->heigh), mt_rand(0, $this->width), mt_rand(0, $this->heigh), $color);
    }
    for ($i = 0; $i < 150; $i++) {
      $color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
      imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->heigh), &#39;#&#39;, $color);
    }
  }

  //输出图像
  private function outPut()
  {
    header('Content-Type: image/png');
    imagepng($this->img);
    imagedestroy($this->img);
  }

  //对外生成
  public function doImg()
  {

    $this->createBg();   //1.创建验证码背景
    $this->createCode();  //2.生成随机码
    $this->createLine();  //3.生成线条和雪花
    $this->createFont();  //4.生成文字
    $this->outPut();    //5.输出验证码图像
  }

  //获取验证码
  public function getCode()
  {
    return strtolower($this->code);
  }

}
로그인 후 복사

4. 테스트

테스트 코드:

<?php
/**
 * Created by PhpStorm.
 * User: andy
 * Date: 16-12-22
 * Time: 下午1:20
 */

define(&#39;ROOT_PATH&#39;, dirname(__FILE__));
require_once ROOT_PATH.&#39;/includes/ValidateCode.class.php&#39;;

$_vc=new ValidateCode();
echo $_vc->doImg();
로그인 후 복사

인증 코드 생성:

5 .신청하세요

 <label>
<img src="../config/code.php" onclick="javascript:this.src=&#39;../config/code.php?tm=&#39;+Math.random();" />
</label>
로그인 후 복사

위의 onclick 코드는 인증코드 이미지를 클릭하면 자동으로 인증코드를 새로고침할 수 있는 코드입니다.

code.php:

<?php
/**
 * Created by PhpStorm.
 * User: andy
 * Date: 16-12-22
 * Time: 下午3:43
 */
require substr(dirname(__FILE__),0,-7).&#39;/init.inc.php&#39;;

$_vc=new ValidateCode();
echo $_vc->doImg();
$_SESSION[&#39;ValidateCode&#39;]=$_vc->getCode();
로그인 후 복사

6. 요약

독립적인 테스트 과정에서는 아무런 문제도 발견되지 않았는데, 프로젝트에 적용해보니 처음에 인증코드 이미지가 생성되지 않는 것을 발견했습니다. 온라인으로 검색해보니 outPut() 함수에서

In header('Content-Type: image/png');, ob_clean() 코드 한 줄이 이 코드 줄 앞에 추가된다고 하는데, 인증 코드 문제를 해결할 수 있습니다. 이 방법은 간단하지만 db_clean() 함수가 출력 버퍼의 내용을 삭제하므로 버퍼링된 데이터에 다른 문제가 발생할 수 있습니다.

관련 추천:

php 인증 코드 클래스 예시 공유

php 인증 코드 예시 및 아이디어 분석


위 내용은 PHP 확인 코드 클래스 ValidateCode의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!