How to make your captcha php

Learn how to create your own captcha using PHP, with an example code that you can implement quickly.

Creating a Captcha with PHP

A Captcha (Completely Automated Public Turing test to tell Computers and Humans Apart) is a type of challenge-response test used in computing to determine whether or not the user is human. Captchas are commonly used to prevent automated abuse of online services such as registration forms and login pages.

Creating a captcha with PHP is easy. The first step is to create the image. This can be done with the GD library, which is a set of functions for manipulating images. The code below creates a 200-by-50 image with a white background and a black border.

$image = imagecreatetruecolor(200, 50);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 200, 50, $white);
imagerectangle($image, 0, 0, 199, 49, $black);

Once the image is created, the next step is to add the text. This can be done with the imagestring() function. The code below adds the text “CAPTCHA” to the image at coordinates (10,10).

imagestring($image, 5, 10, 10, 'CAPTCHA', $black);

The next step is to add the random text. This can be done with the rand() and mt_rand() functions. The code below adds a random string of 8 characters to the image at coordinates (10, 30).

$string = '';
for ($i = 0; $i < 8; $i++) {
  $string .= chr(rand(97, 122));
}
imagestring($image, 5, 10, 30, $string, $black);

The last step is to output the image. This can be done with the imagepng() function. The code below outputs the image to the browser as a PNG file.

header('Content-type: image/png');
imagepng($image);

That’s it! You now have a basic captcha system in place. The code above is just a starting point; you can customize it to suit your needs. For example, you can add different fonts, colors, shapes, and backgrounds.

Answers (0)