I haven't posted anything here for quite a while so I decided to set about making a set of functions to create a captcha.
To create the captcha image, you can get a captcha from the file you save this snippet in, with a GET extension of make=true, eg:
Alternatively you can directly use make_image().
To check if a user has entered a correct captcha, use the function correct_captcha which returns 0 on failure and 1 on success.
captcha_errormsg returns the error message as a string in applicable.
Note: This has a default of "You filled the captcha incorrectly." even if there is no error.
captcha_errornumeric returns the error message in number format.
If captcha_errornumeric returns 1, the user did not enter a captcha.
If captcha_errornumeric returns 2, somehow the $_SESSION['string'] became unset.
If captcha_errornumeric returns 3, the user entered an incorrect captcha.
Note: This function has a default of 3, even if there is no error.
Note: Functions correct_captcha, captcha_errormsg and captcha_errornumeric require the parameter of the captcha the user enters. Eg:
Note: Captchas are case-sensitive.
The code submitted as the snippet should be placed in PHP file, eg. captcha.php
There are several ways to use this snippet, a full example is given here:
Note: The working example file was named form.php whilst running it. To change that, edit the HTML containing "form.php" to your filename.
Any questions/suggestions/bugs/issues/feedback are all welcome.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
function make_image(){
$im = imagecreate(200, 40);
$b = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
$a = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
$array = characters();
$string = '';
for ($i = 0; $i < 6; $i++) {
$r = rand(0,(count($array)-1));
$string.=$array[$r];
}
$_SESSION['string'] = $string;
imagestring($im, 5, rand(1,130), rand(1,20), $string, $a);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
}
function characters(){
return array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9","-","_","@","!");
}
function correct_captcha($str){
if (!$_SESSION['string']) return 0;
if ($str !== $_SESSION['string']) return 0;
else return 1;
}
function captcha_errormsg($str){
if (($str == "") || ($_SESSION['string'] == "")) return "You did not fill in the captcha.";
else return "You filled the captcha incorrectly.";
}
function captch_errornumeric($str) {
if ($str == "") return 1;
if ($_SESSION['string'] == "") return 2;
return 3;
}
if ($_GET['make'] == "true") make_image();
?>