Currently, forms on the Web page are usually embedded with a verification code to prevent servers from being attacked by malicious DoS attacks or hackers using machine programs to automatically post psoriasis advertisements.
The simple implementation method in PHP is as follows:
1. First, generate an image and add some interference pixels or line segments before the form page is displayed (to prevent automatic OCR)
The PHP program automatically generates a random string of numbers and letters to be verified, and calls the imagettftext () function to draw the image,
And save the string to the session-level variable.
The following is the authcode. php file that generates the verification code (requires the support of the php gd library; otherwise, the verification code image cannot be displayed normally)
<? PHP
Session_start ();
Header ("Content-Type: image/PNG ");
Srand (double) microtime () * 1000000 );
$ Imagewidth = 60;
$ Imageheight = 20;
$ Authimage = imagecreate ($ imagewidth, $ imageheight );
$ Black = imagecolorallocate ($ authimage, 0, 0, 0 );
$ White = imagecolorallocate ($ authimage, 255,255,255 );
$ Red = imagecolorallocate ($ authimage, 255, 0, 0 );
$ Gray = imagecolorallocate ($ authimage, 200,200,200 );
// The background color is gray.
Imagefill ($ authimage, 0, 0, $ gray );
// Randomly generate some interference pixels
For ($ I = 0; I I <400; $ I ++)
{
$ Randcolor = imagecolorallocate ($ authimage, Rand (10,255), Rand (10,255), Rand (10,255 ));
Imagesetpixel ($ authimage, Rand () % $ imagewidth, Rand () % $ imageheight, $ randcolor );
}
// Draw several random line segments
For ($ I = 0; $ I <6; $ I ++)
{
Imageline ($ authimage, Rand () % $ imagewidth, Rand () % $ imageheight,
Rand () % $ imagewidth, Rand () % $ imageheight, $ black );
}
// Generate a verification string
$ Array = "0123456789 abcdefghijklmnopqrstuvwxyz ";
For ($ I = 0; $ I <4; $ I ++)
{
$ Authcode. = substr ($ array, Rand (0, 35), 1 );
}
Imagettftext ($ authimage, 20, 0, 0, $ imageheight, $ red, 'arial. ttf', $ authcode );
Imagepng ($ authimage );
Imagedestroy ($ authimage );
$ _ Session ['authcode'] = $ authcode;
?>
2. Add a verification code image to the form.
Verification Code: <input type = "text" name = "authcode" id = "textfield"/>
<br/>
3. After the user submits the input, the user can verify that the entered verification code is consistent with the verification code saved on the server.
If (strcmp ($ _ session ['authcode'], $ _ post ['authcode'])
{
Echo "<SCRIPT> alert ('incorrect verification code! '); </SCRIPT> ";
}