Home >Backend Development >PHP Tutorial >Practical PHP verification code code (1/2)_PHP tutorial
Verification codes are indispensable in developing applications. We often encounter problems with being registered by a machine. Verification codes can effectively prevent such behavior. Let's take a look at the code I provided.
Verification codes are indispensable in developing applications. We often encounter problems with being registered by a machine. Verification codes can effectively prevent such behavior. Let’s take a look at the code I provided.
session_start();
class authnum {
//Image object, width, height, verification code length
private $im;
private $im_width;
private $im_height;
private $len;
//Random string, y-axis coordinate value, random color
private $randnum;
private $y;
private $randcolor;
//The background color is red, green and blue, the default is light gray
public $red=238;
public $green=238;
public $blue=238;
/**
* Optional settings: verification code type, interference points, interference lines, y-axis randomization
* Set to false to disable
**/
//The default is a mixture of uppercase and lowercase numbers, 1 2 3 represents lowercase, uppercase, and numeric respectively
public $ext_num_type='';
public $ext_pixel = false ; //Interference point
public $ext_line = false; //Interference line
public $ext_rand_y= true; //Y-axis random
function __construct ($len=4,$im_width='',$ im_height=25) {
// Verification code length, image width, and height are required data when instantiating the class
$this->len = $len; $im_width = $len * 15;
$this->im_width = $im_width;
$this->im_height= $im_height;
$this->im = imagecreate($im_width,$im_height);
}
/ / Set the image background color, the default is light gray background
function set_bgcolor () {
imagecolorallocate($this->im,$this->red,$this->green,$this-> blue);
}
//Get any digit random code
function get_randnum () {
$an1 = 'abcdefghijklmnopqrstuvwxyz';
$an2 = 'abcdefghijklmnopqrstuvwxyz';
$an3 = '0123456789';
if ($this->ext_num_type == '') $str = $an1.$an2.$an3;
if ($this->ext_num_type == 1) $str = $an1;
if ($this->ext_num_type == 2) $str = $an2;
if ($this->ext_num_type == 3) $str = $an3;
for ($i = 0; $i < $this->len; $i++) {
$start = rand(1,strlen($str) - 1);
$randnum .= substr ($str,$start,1);
}
$this->randnum = $randnum;
$_session[an] = $this->randnum;
}
// Get the y-axis of the verification code image
function get_y () {
if ($this->ext_rand_y) $this->y = rand(5, $this->im_height/5);
else $this->y = $this->im_height / 4 ;
}
1 2