Creating a CAPTCHA with PHP - Writing the text to the image (Page 4 of 6 ) Now that we have the text to write we actually need to write it to the image and display it to the user. This is made fairly easy with GD. <?php /* Now for the GD stuff, for ease of use lets create the image from a background image. */
$captcha = imagecreatefrompng("./captcha.png");
/* Lets set the colours, the colour $line is used to generate lines. Using a blue misty colours. The colour codes are in RGB */
$black = imagecolorallocate($captcha, 0, 0, 0); $line = imagecolorallocate($captcha,233,239,239);
/* Now to make it a little bit harder for any bots to break, assuming they can break it so far. Lets add some lines in (static lines) to attempt to make the bots life a little harder */ imageline($captcha,0,0,39,29,$line); imageline($captcha,40,0,64,29,$line); ?> |
As you can see from the code above we are loading the basic image from CAPTCHA.png instead of building the image itself which could be a little complex for this basic tutorial. When we use colour in GD we need to allocate the colour to a variable, we do this with imagecolorallocate(). Once we have the colours stored inside of the respected variables we then use them to draw the lines through the image. This is to make the robots job of cracking the captcha just that little bit harder, because we are nice to the robots like that :) Finally we have to write the text to the image which is made easy with imagestring() . The only thing left to do on this image is to output it which is done by setting the content type of the page to image/png with header() and outputting the image to the browser with imagepng(). It is also worth mentioning that the string is encrypted and stored in the session variable $_SESSION['key'] <?php /* Now for the all important writing of the randomly generated string to the image. */ imagestring($captcha, 5, 20, 10, $string, $black);
/* Encrypt and store the key inside of a session */
$_SESSION['key'] = md5($string);
/* Output the image */ header("Content-type: image/png"); imagepng($captcha); ?> |
Next: Check if the user entered the code correctly >>
More Miscellaneous Articles More By Andrew Walsh | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
| |