Tag: verification

PHP Image Verification in Forms

One of the most common ways to stop bots and spammers from generating spam in people’s websites is using some form of image verification. This can be done very easily with just PHP and Sessions. Using image verification acts as a human detector, to make sure the viewer of that page is not a bot of some kind. Bots can cause damage to your server by overloading it with spammed content and flooding your boards with unwanted links and text.

Let’s say we have a form that submits a few fields and possibly a file:

[code lang=”html”]

Field 1:
Field 2:
File:

[/code]

Now, this form will submit three variables: field1, field2, and the file.

This form does not have any image verification added in. So any bot could simply process this page over and over to flood the server with crap. 🙁 So we are going to add a simple image verification to the form. To do this we make image.php:

[code lang=”php”]

[/code]

Now we must add the field to our form:

[code lang=”html”]
Verification:  

[/code]

Notice I used the class “imgverification.” We must add this to our <head> tags of the page:

[code lang=”html”]

[/code]

We must also make sure we include our session_start() on all pages we use session variables on. So on our form page, the image page, and submit page.

Now when the form is submitted to submit.php we check the submitted input for $_POST[“verification”] to $_SESSION[“md5_image_verification”].

[code lang=”php”]

[/code]

function simple_image($width,$height){
$image = imagecreate($width,$height);

$alphanum = “ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”;
$rand = strtoupper(substr(str_shuffle($alphanum),0,6));
$_SESSION[‘simp_image_verification’] = $rand;
$_SESSION[‘md5_simp_image_verification’] = md5($rand);

$bgColor = imagecolorallocate($image, 231,231,231);
$textColor = imagecolorallocate($image, 0,0,0);
$textSize = imagefontheight(1);
imagestring ($image, 5, 8, 2, $_SESSION[‘simp_image_verification’], $textColor);
header(“Expires: Mon, 26 Jul 1997 05:00:00 GMT”);
header(“Last-Modified: ” . gmdate(“D, d M Y H:i:s”) . ” GMT”);
header(“Cache-Control: no-store, no-cache, must-revalidate”);
header(“Cache-Control: post-check=0, pre-check=0”, false);
header(“Pragma: no-cache”);
header(‘Content-type: image/jpeg’);
imagejpeg($image);
imagedestroy($image);
return true;
}

Filed under: TutorialsTagged with: , , ,