欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php实现加减法验证码代码

程序员文章站 2022-07-19 12:58:17
复制代码 代码如下:

复制代码 代码如下:

<?php
/*图片验证码文件,加减计算方式*/

class imagecode{

 private $jiashu  = 0;        //加数或者减数
 private $jianshu = 0;        //被加数或者被减数
 private $yunsuan = '';       //运算符
 private $deshu   = 0;        //得数
 private $string  = '';       //字符串样式
 private $img;                //图片对象
 private $width   = 100;      //图片宽度
 private $height  = 50;       //图片高度
 private $ttf     = 'num.ttf';//字体文件
 private $session = 'code';   //session变量

 private function jiashu(){
  header('content-type:image/png');
  $this -> jiashu  = rand(1, 10);
  $this -> jianshu = rand(1, 10);
  $this -> yunsuan= $this -> jiashu > $this -> jianshu ? '-' : '+';
  $this -> deshu   = $this -> jiashu > $this -> jianshu ? $this -> jiashu - $this -> jianshu : $this -> jiashu + $this -> jianshu;
 }

 public function show( $w = 100, $h = 50, $t = 'num.ttf', $code = 'code' ){
  $this -> jiashu();
  $this -> string = $this -> jiashu . $this -> yunsuan . $this -> jianshu . '= ? ';
  $this -> width  = $w;
  $this -> height = $h;
  $this -> ttf    = $t;
  $this -> session= $code;
  session_start();
  $_session[$this -> session] = $this -> deshu;
  $this -> images();
 }

 private function images(){
  $this -> img = imagecreate($this -> width, $this -> height);
  $background_color = imagecolorallocate ($this -> img, 255, 255, 255);
  imagecolortransparent($this -> img, $background_color);
        imagettftext($this -> img, 14, 0, 1, 20, imagecolorallocate ($this -> img, 0, 0, 0), $this -> ttf, $this -> string );
  $this -> echoimages();
 }

 private function echoimages(){
  imagepng($this -> img);
  imagedestroy($this -> img);
 }

}

$imagecode = new imagecode;
$imagecode -> show(130, 35, 'num.ttf', 'code');