If you are looking for simple and easiest CAPTCHA code using PHP. In this tutorial, I am going to explain how to implement own CAPTCHA in PHP with the use of some existing image functions in PHP for creating an image.
A CAPTCHA is a random string which is basically used to protect the website from spam.Here I am going to show you the one of the easiest CAPTCHA code and you can easily add into your site. Here I have generated a character with using some string functions and loop.
1 2 3 4 5 6 7 8 9 | $charlist = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789#*&^$@%><"; $cnt = strlen($charlist) - 1; $char = ""; while(strlen($char) < 6) { $char .= $charlist[rand(0,$cnt)]; } |
Next, place below code and here I have defined png image to create a CAPTCHA but you can use JPEG, BMP and GIF also. In the header, ‘Content-Length’ will be png if you are going to use imagepng and jpeg, if imagejpeg.In imagecreate function, you need to pass own width and height for the image.
1 2 3 4 5 6 7 8 9 10 11 12 13 | header("Content-type: image/png"); $imghandle = imagecreate(width,height) or die('Cannot initialize new GD image stream'); /* setting the background, text and noise colours here */ $background_color = imagecolorallocate($imghandle,0,0,0); $text_color = imagecolorallocate($imghandle,255,255,255); $noise_color = imagecolorallocate($imghandle, 100, 120, 180); imagestring($imghandle,5,5,8,$char,$text_color); /* output captcha image to browser */ imagepng($imghandle); imagedestroy($imghandle);//destroy the image instance |
Now, When submitting CAPTCHA code, have to validate captcha text entry and without validation, CAPTCHA is useless. so to validate CAPTCHA, first we take CAPTCHA code into a SESSION variable and compare it with the user entered text passed as POST data.
1 2 3 4 |
That’s it.What do you think is this easiest technique I’ve mentioned above? Why or why not? Share your thoughts and questions in the comments.
Thanks for reading and feel free to share your thoughts, don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.
Comments (1)