Programming: PHP image captcha code

programming php image-capture-code

Here I would like to present my small but nice capture code solution, which I programmed some time ago. I was tired, also with regard to the german DSGVO (privacy laws), to include capture solutions of external providers. In addition, various privacy browsers block e.g. also javascripts, so that an external image capture module for e.g. the own contact or registration form no longer works.

An own solution had to be found, and that of an image capture code to protect against spam with PHP 7 or 8 is programmed quickly and easily. The font used in this example is Yellowtail-Regular in OTF format (OpenType Font), but there is no special reason for this. PHP 7 and higher can handle such OTF files with imagefttext. You can download a corresponding file for the desired font anywhere on the Internet.

kraken l.jpg

php image-capture-code previewI decided to draw a few random circles in the background of the captcha, and randomly rotate, offset, and color the letters and numbers slightly differently to prevent potential bots from reading the codes automatically.

If you don't like this, you can of course change and adapt it to your wishes.

Table of contents:

Step 1 - Generate random string (code) and store it in database

You basically need 3 functions, which I wrote in a class called Database.php together with the connection to the MySQL database.

//generates a random code and writes it to the database.
function createCapture(){
$code = $this->getRandomCode(6, true);

$q = "INSERT INTO ".TABLE_CAPTURE." (code) VALUES ('".$code."')";
return $this->insert_id();

//loads the corresponding code from the database using the assigned ID
function getCaptureCode($id){
$id = (int)$id;
$code = "";

$q = "SELECT code FROM ".TABLE_CAPTURE." WHERE Id='".$id."'";
$res = $this->query($q);
if ($data = $this->fetch($res)){
$code = $data['code'];
return $code;

//checks if the entered code matches the ID and the corresponding code from the database
function checkCaptureCode($id, $code){
$len = strlen($code);
if ($len<=0 || $len>8)
return false;

$valid = false;
$id = (int)$id;

$valid = ($this->getCaptureCode($id) == $code);
$this->query("DELETE FROM ".TABLE_CAPTURE." WHERE Id='".$id."'");
return $valid;

Step 2 - PHP script to generate the image capture code into an image file (PNG)

You can simply copy the following code into a new PHP file called gen_capture.php. The corresponding parts of the code are only minimally commented, but should be easy to understand. You may have to include your database.php, if it hasn't already been loaded (globally) somewhere before.

global $database;
$id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? (int)$_GET['id'] : 0;

//Load Code by ID
if ($id>0)
$code = $database->getCaptureCode($id);
$code = "1245678";

//define Font-File
$font_file = './Yellowtail-Regular.otf';
$font_size = 26;

//define Size of Capture Image
$width = 200;
$height = 100;

//Create Image
$im = imagecreatetruecolor($width, $height);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

//Create some random colors for background cycles
$color_mix = array();
for ($i=0; $i<strlen($code); $i++)
$color_mix[$i] = imagecolorallocate($im, mt_rand(0, 100), 0x00, mt_rand(100, 255));

//background black
imagefilledrectangle($im, 0, 0, $width-1, $height-1, $black);

//draw some random cycles
$x = 0;
$y = ($height/2);
$step_x = (int)($width/strlen($code));
for ($i=0; $i<5; $i++)
$size = mt_rand($font_size*2, $font_size*3);
imagefilledellipse($im, $x, $y, $size, $size, $color_mix[$i]);

$x += mt_rand($step_x*1.5, $step_x*2);

//draw the Code / char by char
$x = $font_size;
$y = ($height/2) + ($font_size/2);
for ($i=0; $i<strlen($code); $i++)
$angle = (mt_rand(0,1)==0) ? mt_rand(1, 30) : mt_rand(315, 359);
$text = substr($code, $i, 1);

imagefttext($im, $font_size, $angle, $x, $y, imagecolorallocate($im, mt_rand(150,255), 0x00, 0x00), $font_file, $text);

$x += mt_rand($font_size*0.8, $font_size*1.1);

//return image capture as png, cleanup and finish.
header('Content-Type: image/png');

Step 3 - Integrate image capture code into you HTML form

In the respective form on your site (e.g. contact form) you can now integrate the finished image capture module. To do so, call the createCapture() function and get the corresponding ID of the code. This ID (capture_id) is passed together with the user input (capture) and evaluated after submitting the form.

<?php $capture_id = $database->createCapture(); ?>
<img src="gen_capture.php?ìd=<?php echo $capture_id; ?>" width="200">
<input type="text" name="capture" placeholder="Enter Code">
<input type="hidden" name="capture_id" value="<?php echo $capture_id; ?>">

Afterwards you can easily check if the user input was correct by calling checkCaptureCode(). Here the code is loaded from the database based on the ID and compared to the user input.

$capture_id = (int)$_POST['capture_id'];
$capture = $database->filterInput($_POST['capture']);
if (!$database->checkCaptureCode($capture_id, $capture)){
$error = "&bull; ".ERROR_CAPTURE_CODE."<br>";

That's about it. Hope the code is clear, which I'm assuming it is. Feedback, praise and constructive criticism welcome! 😉

kraken l.jpg

Author: Sascha from

Author: Sascha

Some words about myself. My name is Sascha - i'm a software developer, trader and martial artist from germany. Besides programming, trading and martial arts some of my interests and hobbies are cooking, fitness and hearing loud heavy metal music. :D

This might also be interesting for you

Program your own Screen Recorder / Capture Software

While searching for an easy to use screen recorder tool, I stumbled across all kinds of free and paid software solutions. From my point of view, pretty much all of them were either completely overloaded, difficult or complicated to use. Others were just expensive in relation to the functionality. My conclusion: Program yourself! Table of … Continue reading "Program your own Screen Recorder / Capture Software"

Unity 2D Platformer - Level Generator

For some time now I have been experimenting here and there with the 2D and 3D engine Unity. Especially the programming of a 2D-Platformers has been very interesting for me. However, programming a 2D game (if you are a programmer) is not the biggest problem, but in my opinion the look, because I am not … Continue reading "Unity 2D Platformer - Level Generator"

self-construction - DynDNS-Alternative

If you already have your own webserver/webspace on the Internet and some programming knowledge, you can save yourself a service like & Co. without much effort if you want to access parts of your home network from the road. Such services provide a host name/URL (e.g. which is then forwarded to the IP … Continue reading "self-construction - DynDNS-Alternative"

Telegram Messenger and the Bot API - Part 2

In the first part - Telegram Messenger and the Bot API - I explained some basics how to set up a telegram bot and how to use it to send messages, states, informations and more to your . Since this tool has proven to be very practical, I decided to take up the previous article … Continue reading "Telegram Messenger and the Bot API - Part 2"

Training equipment: Makiwara 2.0

A Makiwara is a piece of sports equipment originating from Japan, which in karate is known mainly as a wooden hitting post. In the past (and partly still today) a makiwara is made of a flexible and non-splintering wooden board. One end of the board is driven vertically into the ground, and the other end … Continue reading "Training equipment: Makiwara 2.0"

Leave a Reply

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

I have read and accepted the privacy policy!