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"

Arduino Fitnessboard v1 - Experiment

On the weekend I fortunately had some time for handicrafts and a nice idea for a fitness board for training at home, which is operated from the push-up position. A video can be found further down in this article and on the Youtube channel of Table of contents:Building  an Arduino Fitness BoardFitnessboard - RequirementsFitnessboard … Continue reading "Arduino Fitnessboard v1 - Experiment"

Trading-Journal: Crypto Trading Bot for Kraken

Every halfway professional trader should of course keep a trading journal to record his trades and to be able to evaluate them later. Some good trading software offers already integrated solutions, but that didn't stop me from programming my own software for our Project and connecting it to our trading system. In addition to … Continue reading "Trading-Journal: Crypto Trading Bot for Kraken"

pi_robot - Playing with Raspberry Pi, iPad and some Code

The Raspberry Pi is still one of the most popular mini computers, not only among hobbyists. Cost-effective (about 30 to 40,- EUR depending on the model), flexible in the field of application and at the latest since the equipped with enough CPU power and memory to solve even more complex tasks. With the 1.2 GHz … Continue reading "pi_robot - Playing with Raspberry Pi, iPad and some Code"

Flashing firmware - ESP8266-WiFi-Module

Since I recently started to deal more intensively with the topics "Smart Home" and "Home automation" I decided to publish some of my construction sites, stumbling blocks and solutions here. As already mentioned in the article about my Smart-Home-Project V1 I use the WLAN module , because it is small, reliable and cheap. In this … Continue reading "Flashing firmware - ESP8266-WiFi-Module"

Leave a Reply

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

I have read and accepted the privacy policy!