Рубрики
Uncategorized

Проверка кода PHP определение класса генерации кода и простой пример использования

Автор оригинала: David Wong.

В этой статье описывается определение класса генерации кода PHP и его простое использование. Для вашей справки приведем следующие сведения:

код. php

number = $number;
    $this->codeType = $codeType;
    $this->width = $width;
    $this->height = $height;
    $this->code = $this->createCode();
  }
 
  /**
   *Destruction of resources
   */
  public function __destruct()
  {
    imagedestroy($this->image);
  }
 
  /**
   *Triggered when code is called externally
   * @param $name
   * @return bool
   */
  public function __get($name)
  {
    if ('code' == $name) {
      return $this->$name;
    } else {
      return false;
    }
  }
 
  /**
   *Generate code
   */
  protected function createCode()
  {
    switch ($this->codeType) {
      case 0:
        $code = $this->getNum();
        break;
      case 1:
        $code = $this->getChar();
        break;
      case 2:
        $code = $this->getNumChar();
        break;
      default:
        Die ('wrong style ');
    }
    return $code;
  }
 
  /**
   *Digital verification code
   * @return string
   */
  protected function getNum()
  {
    $str = join('', range(0,9));
    return substr(str_shuffle($str), 0, $this->number);
  }
 
  /**
   *Character verification code
   * @return string
   */
  protected function getChar()
  {
    $str = join('', range('a', 'z'));
    $str = $str . strtoupper($str);
    return substr(str_shuffle($str), 0, $this->number);
  }
 
  /**
   *Mixed character and digit captcha
   * @return string
   */
  protected function getNumChar()
  {
    $num = join('', range(0, 9));
    $str = join('', range('a', 'z'));
    $str_big = strtoupper($str);
    $numChar = $num . $str . $str_big;
    return substr(str_shuffle($numChar), 0, $this->number);
  }
 
  /**
   *Generating images
   */
  protected function createImage()
  {
    $this->image = imagecreatetruecolor($this->width, $this->height);
  }
 
  /**
   *Fill background color
   */
  protected function fillColor()
  {
    imagefill($this->image, 0, 0, $this->lightColor());
  }
 
  /**
   *Light color
   * @return int
   */
  protected function lightColor()
  {
    return imagecolorallocate($this->image, mt_rand(170, 255), mt_rand(170, 255), mt_rand(170, 255));
  }
 
  /**
   *Dark color
   * @return int
   */
  protected function darkColor()
  {
    return imagecolorallocate($this->image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
  }
 
  /**
   *Add captcha character
   */
  protected function drawChar()
  {
    $width = ceil($this->width/$this->number);
    for ($i = 0; $i < $this->number; $i++) {
      $x = mt_rand($i * ($width - 5), ($i + 1) * ($width - 5));
      $y = mt_rand(0, $this->height - 15);
      imagechar($this->image, 5, $x, $y, $this->code[$i], $this->darkColor());
    }
  }
 
  /**
   *Add interference point
   */
  protected function drawDisturb()
  {
    for ($i= 0; $i < 100; $i++) {
      imagesetpixel($this->image, mt_rand(0, $this->width), mt_rand(0, $this->height), $this->darkColor());
    }
  }
 
  /**
   *Add interference line
   */
  protected function drawArc()
  {
    for ($i = 0; $i < $this->number - 3; $i++) {
      imagearc($this->image, mt_rand(5, $this->width), mt_rand(5, $this->height), mt_rand(5, $this->width), mt_rand(5, $this->height),mt_rand(0, 70), mt_rand(300, 360), $this->darkColor());
    }
  }
 
  /**
   *Output display
   */
  protected function show()
  {
    header('Content-Type:image/png');
    imagepng($this->image);
  }
 
  /**
   *External image
   */
  public function outImage()
  {
    $this - > createimage(); // create canvas
    $this - > fillcolor(); // fill background color
    $this - > drawchar(); // add verification character
    $this - > drawdisturb(); // add interference point
    $this - > drawarc(); // add interference line
    $this - > show(); // output
  }
}

Покажи капчу.. Сохраните капчу и время истечения срока действия

outImage();
session_start();
$_SESSION['code'] = [
  'code' => $code->code,
  'exp_time' => time() + (60 * 60 * 10),
];

Более заинтересованные читатели, интересующиеся контентом, связанным с PHP, могут просмотреть специальные разделы этого веб-сайта: “Краткое изложение навыков работы с графикой и изображениями PHP”, “Навыки работы с массивом PHP (массив)”, “Учебник по структуре данных и алгоритмам PHP”, “Краткое изложение алгоритмов программирования PHP”, “Краткое изложение навыков математических операций PHP”, “Краткое изложение использования строк PHP (строк)” и “Краткое изложение навыков работы с общими базами данных PHP” “

Я надеюсь, что эта статья поможет вам в программировании на PHP.