4 * Ptitcaptcha : simple php captcha system
6 * @author Jean-Pierre Morfin
7 * @license Creative Commons By
8 * @license http://creativecommons.org/licenses/by/2.0/fr/
11 /* Change it to have a specific encoding ! */
12 define("PTITCAPTCHA_ENTROPY","sourceml ptitcaptcha entropy");
14 /* Choose length (max 32) */
15 define("PTITCAPTCHA_LENGTH",5);
17 $GLOBALS["ptitcaptcha_akey"] = md5(uniqid(rand(), true));
20 * Helper to generate html form tags
23 class PtitCaptchaHelper
28 * @param string $baseuri : relative or absolute path to folder containing this file on web
31 function generateImgTags($baseuri)
33 return "<a class=\"ptitcaptcha\" href=\"#\"><img alt=\"???\" title=\"?\"".
34 " src=\"".$baseuri."ptitcaptcha.php?pck=".$GLOBALS['ptitcaptcha_akey']."\"".
35 " id=\"ptitcaptcha\"".
36 " onclick=\"javascript:this.src='".$baseuri."ptitcaptcha.php?pck=".
37 $GLOBALS['ptitcaptcha_akey'].
38 "&z='+Math.random();return false;\" /></a>\n";
42 * Generate hidden tag (must be in a form)
44 * @return input hidden tag
46 function generateHiddenTags()
48 return "<input type=\"hidden\" name=\"ptitcaptcha_key\" value=\"".$GLOBALS['ptitcaptcha_akey']."\"/>";
52 * Generate input tag (must be in a form)
56 function generateInputTags()
58 return "<input type=\"text\" name=\"ptitcaptcha_entry\" id=\"ptitcaptcha_entry\" value=\"\"/>";
62 * Check if user input is correct
64 * @return boolean (true=correct, false=incorrect)
66 function checkCaptcha()
68 if( isset($_POST['ptitcaptcha_entry']) &&
69 $_POST['ptitcaptcha_entry'] == PtitCaptchaHelper::_getDisplayText($_POST['ptitcaptcha_key']))
82 function _getDisplayText($pck) // internal function
84 $src=md5(PTITCAPTCHA_ENTROPY.$pck);
86 for($i=0;$i<PTITCAPTCHA_LENGTH;$i++)
87 $txt.=substr($src,$i*32/PTITCAPTCHA_LENGTH,1);
93 // If script called directly : generate image
94 if(basename($_SERVER["SCRIPT_NAME"])=="ptitcaptcha.php" && isset($_GET["pck"]))
96 $width = PTITCAPTCHA_LENGTH*10+10;
99 $image = imagecreatetruecolor($width, $height);
100 $bgCol = imagecolorallocate($image, rand(128,255), rand(128,255), rand(128,255));
101 imagefilledrectangle($image,0,0,$width,$height,$bgCol);
103 $txt = PtitCaptchaHelper::_getDisplayText($_GET["pck"]);
105 for($c=0;$c<PTITCAPTCHA_LENGTH*2;$c++)
107 $bgCol = imagecolorallocate($image, rand(100,255), rand(100,255), rand(100,255));
111 $h=rand(5,$height/2);
112 imagefilledrectangle($image,$x,$y,$x+$w,$y+$h,$bgCol);
113 imagecolordeallocate($image,$bgCol);
115 for($c=0;$c<PTITCAPTCHA_LENGTH;$c++)
117 $txtCol = imagecolorallocate($image, rand(0,128) , rand(0,128), rand(0,128));
118 imagestring($image,5,5+10*$c,rand(0,10),substr($txt,$c,1),$txtCol);
119 imagecolordeallocate($image,$txtCol);
122 header("Content-type: image/png");
124 imagedestroy($image);