For simplicity of this illustration, we will use random numbers and convert them to images to be used as captcha. Then we will use session and other GD components to generate images. Below is the PHP script, which we call captxt.php <?php //start session which will be used to store generated numbers of validation in the form session_start(); //generate random number between 10,000 and 99999 $number =mt_rand(10000, 99999); //store generate random number to a session $_SESSION['answer']=$number; //create image 50 x 50 pixels $imagecreate = imagecreate(50, 50); // white background and blue text $background = imagecolorallocate($imagecreate, 255, 255, 255); $textcolor = imagecolorallocate($imagecreate, 0, 0, 255); // write the string at the top left imagestring($imagecreate, 5, 5, 10, $number, $textcolor); // output the image header("Content-type: image/png"); $image= imagepng($imagecreate); ?> Let's discuss the process for you to improve this design: 1. session_start(); is required in the first line of every PHP script if we want to store variables in the session. Storing variables in the session makes it available for use in other files that also use the session. This will be used to test whether the generated random number matches the one typed in by the user. 2. $number =mt_rand(10000, 99999); will generate random numbers in the range of 10,000 to 99,999 and store them the $number variable. 3. $_SESSION['answer']=$number; will store the generated random number to a session array so that it can be used in the PHP form script that will test if the user's answer matches the generated code. 4. And finally this piece code: //create image 50 x 50 pixels $imagecreate = imagecreate(50, 50); // white background and blue text $background = imagecolorallocate($imagecreate, 255, 255, 255); $textcolor = imagecolorallocate($imagecreate, 0, 0, 255); // write the string at the top left imagestring($imagecreate, 5, 5, 10, $number, $textcolor); // output the image header("Content-type: image/png"); $image= imagepng($imagecreate); The function creates a space 50 x 50 pixel square, using a white background and blue text. This is purely customizable; for the sake of simplicity we do not include complex backgrounds, as you have seen in some captcha systems.
blog comments powered by Disqus |
|
|
|
|
|
|
|