Make a Custom Captcha in PHP

If you make a custom captcha using php then you should follow below code.

First i have generate random string using below code in captcha.php

<?php

session_start();
 
$string = '';
 
for ($i = 0; $i < 5; $i++) {
    // this numbers refer to numbers of the ascii table (lower case)
    $string .= chr(rand(97, 122));
}
 
$_SESSION['random_code'] = $string;

Next, i have created a image with its property using some predefined php functions in captcha.php and you can see i have create and defined a fonts directory and download a any font which you like and store that in fonts folder.After that you can put into your code below like i have defined.

Also, here you can see i have defined background color, font color of captcha image.

 
$dir = 'fonts/';
$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 200, 100, 90); // red
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,0,0,$black);
imagettftext ($image, 30, 0, 10, 40, $color, $dir."times_new_yorker.ttf", $_SESSION['random_code']);
header("Content-type: image/png");
imagepng($image);

This is the end of the captcha.php.
Now, i have created a contact form and included captcha.php using below code and check with user input that user enter correct captcha or you can verify the user is human or not on index.php.

<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?><” enctype=”multipart/form-data” method=”post”>
<input name=”name” type=”text” />
<input name=”email” type=”text” /> Email
<textarea name=”message”></textarea>
<img src=”captcha.php” />
<input name=”code” type=”text” /> Are you human?
<input class=”button” name=”submit” type=”submit” value=”Send” />
</form>

Now, run this index.php and see the captcha with contact form.

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *