The simplest example of generating a random verification code Image
The code is as follows:
/** Default homepage **/
Class DefaultController extends AppController
{
Public function index (){
$ Len = 5;
$ Str = "ABCDEFGHIJKLNMPQRSTUVWXYZ123456789 ";
$ Im = imagecreatetruecolor (70, 20 );
$ Bgc = imagecolorallocate ($ im, 255,255,255 );
$ Bgtxt = imagecolorallocate ($ im, 220,220,220 );
// Random color palette
$ Colors = array (
Imagecolorallocate ($ im, 255, 0, 0 ),
Imagecolorallocate ($ im, 0,200, 0 ),
Imagecolorallocate ($ im, 0, 0,255 ),
Imagecolorallocate ($ im, 0, 0, 0 ),
Imagecolorallocate ($ im, 255,128, 0 ),
Imagecolorallocate ($ im, 255,208, 0 ),
Imagecolorallocate ($ im, 98,186,245 ),
);
// Fill in the background color
Imagefill ($ im, 0, 0, $ bgc );
// Obtain random numbers
$ Verify = "";
While (strlen ($ verify) <$ len ){
$ I = strlen ($ verify );
$ Random = $ str [rand (0, strlen ($ str)];
$ Verify. = $ random;
// Draw background text
Imagestring ($ im, 6, ($ I * 10) + 3, rand (0, 6), $ random, $ bgtxt );
// Draw the main text information
Imagestring ($ im, 6, ($ I * 10) + 3, rand (0, 6), $ random, $ colors [rand (0, count ($ colors) -1)]);
}
// Add random colors
For ($ I = 0; I I <100; $ I ++ ){
$ Color = imagecolorallocate ($ im, rand (50,220), rand (50,220), rand (50,220 ));
Imagesetpixel ($ im, rand (0, 70), rand (0, 20), $ color );
}
// Save the verification code to $ _ SESSION
Sess ("verify", $ verify );
// Output the image and release the cache
Header ('content-type: image/png ');
Imagepng ($ im );
Imagedestroy ($ im );
}
};
?>