how to add image capthcha in php
STEP 1 : GENERATE RANDOM STRING
First we create a php file name like captcha.php. then copy this code and paste there.
<?php session_start(); function getRandomCaptchaText($len = 5) { $word = array_merge(range('0', '9'), range('A', 'Z')); shuffle($word); return substr(implode($word), 0, $len); } $ranStr = getRandomCaptchaText(); $_SESSION["captcha_text"] = $ranStr; $height = 40; //CAPTCHA image height $width = 160; //CAPTCHA image width $font_size = 22; //CAPTCHA Font size $image_p = imagecreate($width, $height); $graybg = imagecolorallocate($image_p, 245, 245, 245); $textcolor = imagecolorallocate($image_p, 34, 34, 34); imagefttext($image_p, $font_size, -2, 15, 26, $textcolor, 'font/liberation-mono.regular.ttf', $ranStr); imagepng($image_p); ?>
NOTE : Please make a font folder and place a any font ttf file. As we hightlight on above
Step 2 : After All this then Please create a demo.php file.
<head> <title>Captcha Image </title> <script type="text/javascript"> function reloadCaptcha() { img = document.getElementById("new-captcha"); img.src="captcha.php?rand_number=" + Math.random(); } </script> </head> <body > <form type=post action="#"> <input type=text name="key"> <img src="captcha.php" id="new-captcha"/> <br> <input type=button onClick=reloadCaptcha(); value='Reload image'> <input type=submit value='submit'> </form> </body> </html>
Share
Manish Garg
You can use an existing image for print captcha text
and use the code given below for jpg format
here is a sample image
http://www.developersmap.com/wp-content/uploads/2019/06/cap_bg.jpg