Your own numeric Captcha in PHP

Your own numeric Captcha in PHP

The idea is to send the actual answer to the other side, but with a simple encryption.

// First page variables.

// Create the random numeric code that a user/visitor will have to confirm it.
// 1000-9999 gives 5832 possibilies, strong enough for most captcha uses.
$VerificationCode = rand(1000, 9999);

// This is not a live example, so we’ll give $UserInput a manual value.
// In your own script, you would capture what the user had typed in.
$UserInput = ‘1234′;

// Create a key that only the other side will know.
// Send this key together with the answer the user provided.
$MySeed = 12345;
$VerificationKey = ($VerificationCode + ($MySeed*(int)date(‘d’)));

/*
The key is now made based on your custom value ($MySeed) that only YOU will know. To hack the key, the hacker would have to know it. AND would have to know what you do with it. In this example we keep it dynamic from day to day by multiplying it with the current day extracted from the current date. It’s easy to figure out something else that would be much harder to guess.

Now you send both $UserInput and $VerificationKey to the next page.
*/

// Second page variables and handling.

// This naturally has to match the value in page one.
$MySeed = 12345;

// Decrypt the key
$ReceivedKey = ((int)$VerificationKey – ($MySeed*(int)date(‘d’)));

// Now you can compare the user input with $ReceivedKey
$VerificationStatus = ((int)$UserInput==$ReceivedKey?true:false);

echo ($VerificationStatus?’Accepted’:'Not accepted’);

Representing the random code to the user
When you have created a random number and/or code you can represent it to your visitor like this: . Images are widely used to ask Captcha questions since they are binary with different random colors and shapes that’s hard to scan for a bot that’s scanning the Internet to collect or spam information.

Can I use your image script to show my random codes?
The image script I’ve used above takes a GET variable and prints it on a chosen image. It’s of no good use to anyone else other than an example, as it would be simple to just read the code right out of your source code for a spam-bot. So please make your own :)

Download your own copy WITH deciphering!
To make it easy for you, you can download the image script here and adapt it to your own needs. (This image script is adjusted to receive a key and view it dechiphered, adjust after your own needs. Bots will NOT be able to scan the code from THIS script, unless they know your way of encrypting the key).

Leave a Reply