/**
* Generate Verification Code
* @param int $type 1: pure numerals, 2: Plain Letters, 3: numbers mixed with letters
* @param int $length
* @return String
*/
function buildrandomstring ($type =1, $length =4) {
if ($type = = 1) {
$chars = Join ("", Range (0, 9));
} elseif ($type = = 2) {
$chars = Join ("", Array_merge (Range ("A", "Z"), Range ("A", "Z"));
} elseif ($type = = 3) {
$chars = Join ("", Array_merge (Range ("A", "Z"), Range ("A", "Z"), range (0, 9));
}
if ($length > strlen ($chars)) {
Exit ("Insufficient string length");
}
$chars = Str_shuffle ($chars);
Return substr ($chars, 0, $length);
}
Verify code via GD Library
function Verifyimage ($type =1, $length =4, $pixel =0, $line =0, $sess _name = "Verify") {
Session_Start ();
Create a canvas
$width = 80;
$height = 28;
$image = Imagecreatetruecolor ($width, $height);
$white = Imagecolorallocate ($image, 255, 255, 255);
$black = imagecolorallocate ($image, 0, 0, 0);
Fill the canvas with filled rectangles
Imagefilledrectangle ($image, 1, 1, $width-2, $height-2, $white);
$chars = buildrandomstring ($type, $length);
$_session [$sess _name] = $chars;
$fontfiles = Array ("Msyh. TTF "," MSYHBD. TTF "," Simli. TTF "," SimSun. TTC "," simyou. TTF "," stzhongs. TTF ");
$fontfiles = Array ("Simyou. TTF ");
Because the font file is larger, just keep a font, if the students need to add their own fonts, fonts in your computer's Fonts folder, directly run the input fonts will be able to see the corresponding font
for ($i = 0; $i < $length; $i + +) {
$size = Mt_rand (14, 18);
$angle = Mt_rand (-15, 15);
$x = 5 + $i * $size;
$y = Mt_rand (20, 26);
$fontfile = $fontfiles [Mt_rand (0, Count ($fontfiles)-1)];
Putenv (' gdfontpath= '. Realpath ('. '));
$color = Imagecolorallocate ($image, Mt_rand (), Mt_rand (90, 180), mt_rand (+);
$text = substr ($chars, $i, 1);
Putenv (' gdfontpath= '. Realpath ('. '));
Name the font to be used (note the lack of the. ttf extension)
Imagettftext ($image, $size, $angle, $x, $y, $color, $fontfile, $text);
}
if ($pixel) {
for ($i = 0; $i < $i + +) {
Imagesetpixel ($image, Mt_rand (0, $width-1), Mt_rand (0, $height-1), $black);
}
}
if ($line) {
for ($i = 1; $i < $line; $i + +) {
$color = Imagecolorallocate ($image, Mt_rand (), Mt_rand (90, 180), mt_rand (+);
Imageline ($image, Mt_rand (0, $width-1), Mt_rand (0, $height-1), Mt_rand (0, $width-1), Mt_rand (0, $height -1), $color);
}
}
Header ("Content-type:image/gif");//Set Header information
Imagegif ($image);
Imagedestroy ($image);
}
PHP Verification Code Encapsulation