Copy codeThe Code is as follows:
<? Php
/**
* Vcode
* Param $ w canvas width
* Param $ h canvas height
* Param $ fnum: Number of verification code elements
* Param $ fontsize verification code element size
* Param $ Number of obs interferon
*/
Function vcode ($ w, $ h, $ fnum, $ fontsize, $ obs ){
$ Img = imagecreatetruecolor ($ w, $ h );
$ White = imagecolorallocate ($ img, 255,255,255 );
$ Black = imagecolorallocate ($ img, 0, 0, 0 );
$ Gray = imagecolorallocate ($ img, 180,180,180 );
Imagefill ($ img, 0, 0, $ gray );
For ($ I = 0; $ I <$ obs; $ I ++ ){
Imagesetpixel ($ img, rand (0, $ w), rand (0, $ h), $ black );
}
$ X = ($ w-$ fnum * $ fontsize)/2;
$ Y = $ h/2 + $ fontsize/2;
$ Fontfile = "final/fonts/msyh. ttf ";
$ Arr = array_merge (range (0, 9), range ('A', 'z'), range ('A', 'z '));
Shuffle ($ arr );
$ Str = implode (array_slice ($ arr, 0, $ fnum ));
Imagettftext ($ img, $ fontsize, 0, $ x, $ y, $ black, $ fontfile, $ str );
Header ("content-type: image/jpeg ");
Imagejpeg ($ img );
Imagedestroy ($ img );
}
Vcode (80, 40, 4, 15,100 0 );
Run:
Through this basic exercise, I learned a simple way to solve the problem, meet the requirements of the goal, and do not blindly tap the code.
For example, the core of the verification code is the imagettftext () function, which is used to design the verification code.
Note: The use of the range () function. If a parameter is a character, it must be single or double quotation marks. Otherwise, the header will be considered as output.