| Registration Security Image |
|
Is your website being flooded with new user registrations? If they are legitimate new users that is great. If all the
new users are coming from someone's spam bot, then I can show you how to stop the bot using PHP. The first thing to do is create an image. $img = imagecreate(100,20);This will create a blank image that is 100 pixels wide by 20 pixels high. Next create some colors for the image. //The numbers are the RGB values 0 to 255 $white = imagecolorallocate($img,255,255,255); $blue = imagecolorallocate($img,120,154,188);Now that some colors are defined, it is possible to start drawing on the image. The first thing I did was fill in the background with the blue color. imagefill($img,0,0,$blue);The second and third parameters to imagefill() are the x and y coordinate of where the flood fill should start. I chose the upper left hand corner. Now that we have a blue image that is 100x20 pixels we need to draw a unique string that will be required in your registration form submission. I choose to work with a randomly generated number. I will now show you a little function used to create the random number.
function random_number()
{
srand(time());
$max = getrandmax();
return rand(1,$max) + rand(1, $max);
}
Now that we can generate our random security number, lets draw it on the image.
imagestring($img,5,6,3,random_number(),$white);Don't be confused by the numbers. The first one is the font size which ranges from 1 to 5. The second and third numbers are once again the x and y coordinates. The security image is now complete and ready to be output to the browser. Lets take a look at how to achieve this.
header("Content-type:image/jpeg");
imagejpeg($img);
First we need to let the browser know it is going to be receiving an image of type jpeg with a Content-type header. Then
a simple call to imagejpeg() will stream the image to the browser. Finally we need to free the memory we used to create the image.
imagedestroy($img);To include this image inside a form all you need to do is use an image tag to call the script. <img src="securityImage.php">You can see the complete script below or see it in action here. The script is slightly different from the steps above. I simply stored the random number in a session variable so I could verify the user entered the correct value in the form.
<?
//securityImage.php
session_start();
$img = imagecreate(100,20);
$white = imagecolorallocate($img,255,255,255);
$blue = imagecolorallocate($img,120,154,188);
imagefill($img,0,0,$blue);
$_SESSION["varname"] = random_number();
imagestring($img,5,6,3,$_SESSION["varname"],$white);
header("Content-type:image/jpeg");
imagejpeg($img);
imagedestroy($img);
function random_number()
{
srand(time());
$max = getrandmax();
return rand(1,$max) + rand(1, $max);
}
?>
|