CrankBerry Blog Title
2009


(1) Comment

PHP Image Verification aka Captcha (Basic)

You're making your website and you have forms. Here you are thinking, what if spam bots found my form? What if somebody submitted to my form from their own script? What should I do? Well, there's many things you can do to mitigate your worries but one of the simpler things you could do is having an image verification field in your form. Here's a basic script to generate a random code in image that bots can't read.

This is a simple version of image verification which requires a single script, I'll be uploading one in the future which is more advanced and more customizable.

So lets start, you don't have to modify any of your coding as of so far, all you need to do is add some coding in to enforce the verification. Now open up your favourite text/PHP and create a file called _verify.php. Have you done that yet? Good! Now in the script just copy this code inside (will be attaching as a zip file as well if there's any problems).

<?php

session_start();

//Your Capcha Settings
$use_numbers = TRUE;
$use_upperCase = TRUE;
$use_lowerCase = FALSE;

$code = simple_code(5, $use_numbers , $use_upperCase, $use_lowerCase);

$_SESSION["verify_code"] = md5($code);
$im_height = 25;
$im_width = 150;
 
$im = imagecreate($im_width, $im_height);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
$font_size = 14;
 
imagestring($im, $font_size, 50, 5, $code, $white);
imagejpeg($im, null, 80);

//This is the simple code Generator
function simple_code($code_len = 1, $have_num = TRUE, $have_caps = TRUE, $have_lower = TRUE) {
        if (!$have_num && !$have_caps && !$have_lower) {
                return 'Please Have at Least One Setting On';
        } else {
                //Starting The Code
                $code = ";
               
                for ($i=1; $i<=$code_len; $i++) {
                        //Keep Generating Characters Until its a proper character
                        do {
                                //Is The Code Good
                                $code_ok = TRUE;
                               
                                //Generate the Characters
                                $code_char = rand(48, 122);
                               
                                //Which Codes do they want
                                if (!$have_num && ($code_char>=48 && $code_char<=57)) $code_ok = FALSE;
                                if (!$have_caps && ($code_char>=65 && $code_char<=90)) $code_ok = FALSE;
                                if (!$have_lower && ($code_char>=97 && $code_char<=122)) $code_ok = FALSE;
                               
                                //Bad Chars
                                if (($code_char >= 58 && $code_char<=64) || ($code_char >= 91 && $code_char<=96)) $code_ok = FALSE;
                        } while (!$code_ok);
                       
                        //Add Character to Code
                        $code .= chr($code_char);
                       
                }
               
                return $code;
        }
}
?>

The code is very simple. All you have to do is configure the three settings at the beginning of the code. Currently its set to have numbers and capital letters only, but change it to whatever suits your flavor. I've kept the default length to 5 because if image verification is too long users may not like it. If the code is too short it maybe too easy for bots; thus, five is an acceptable length. The code above integrates a random code generator which I have demonstrated before.

So save the file and lets continue. In your form page add the following code:

Image Verification

<input name="verification" type="text" />

Match This

<img src="_verify.php" />

Format it to however suits your website. Now the above code adds the verification field in your form but does not validate the input yet. That's right, we have to validate the input. To validate with the following before you process your form.

$validatePass = (md5($_POST['verification'])==$_SESSION["verify_code"]) ? 1 : 0;

Now the above code only validates the input, but does not stop the form from processing. The variable $validatePass will be 1 if the verification is correct and 0 if it is not. You'll have to have your code laid out in something like this:

//If Submitting
if (isset($_POST['submit'])) {
        $validatePass = (md5($_POST['verification'])==$_SESSION["verify_code"]) ? 1 : 0;
       
        if ($validatePass) {
                //Run my Form   
        } else {
                echo 'Image verification did not match';       
        }
}

And that is all you need to make your forms bot and spam proof. Do note that this is not a catch all solution, there are other things you need to put in place to secure your environment for your users.

image verification

Problems You May Have

If you are having trouble with loading the image or having the verification working, look at the following checklist. This might help you.

  • Have you enabled GD/GD1 extension on your server/php?
  • Do you have cookies disabled, cookies is required?
  • Did you include session_start() on top of your php file which has the form?
TL
This entry was posted on Thursday, October 8th, 2009 at 12:43 am and is filed under PHP, Scripts and Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
BL

One Response to “PHP Image Verification aka Captcha (Basic)”

  1. php answers php answers says:

    Thanks for this, well written and easy to understand :)

Leave a Reply

Spam protection by WP Captcha-Free