My Captcha doesn't work every time

Discussion in 'PHP' started by rsshostedonmyownsite, Sep 2, 2009.

  1. #1
    I have the following code:

    <script type="text/javascript">
     image = "http://mysite.net/captchaimage.php" //name of the image
          function NewCaptcha() {
          tmp = new Date();
          tmp = "?"+tmp.getTime()
          document.images["captcha"].src = image+tmp 
    }
    </script>
    
    <img src="http://mysite.net/captchaimage.php" alt="CAPTCHA" name="captcha" />
    <br /><div class="attendst">
    Too obscure? <a href="javascript:NewCaptcha()">Reload</a>.</div>			<br />
    
    			<label for="captchafield">Enter the text from the image above.</label><br />
    			<input type="text" name="captcha" id="captchafield" />
    
    PHP:
    Which is connected to this code:

    function createCAPTCHA($ref) {
    	//Create image
    	$captcha = imagecreatefrompng("./captcha.png");
    
    	//Define colours
    	$black = imagecolorallocate($captcha, 0, 0, 0);
    	$line = imagecolorallocate($captcha,0,0,0);
    
    	//Start the session
    	session_start();
    
    	//Use md5 to generate a random string
    	$md5 = md5(microtime() * mktime());
    
    	//We dont need a 32 character long string so we trim it down to 5
    
    	$string = substr($md5,0,5);
    
    	//Add string to image
    	imagestring($captcha, 5, rand(30,90), rand(0,60), $string, $black);
    
    	//Draw lines on image
    	imageline($captcha,rand(30,70),0,rand(0,155),79,$line);
    	imageline($captcha,rand(30,100),0,rand(0,155),79,$line);
    
    
    	//Store string in session	
    	$_SESSION['captchakey'] = md5($string);
    	$_SESSION['ref'] = $ref;
    
    	//Output the image
    	
    	header("Content-type: image/png");
    	imagepng($captcha);
    
    imagedestroy($captcha);
    
    }
    PHP:

    This issue is, sometimes the captcha works and sometimes it doesn't. When it doesn't work it will just give the "incorrect captcha" error. What could be causing the code to not recognize the captcha only sometimes. Anyone have any suggestions?

    Thanks!
     
    rsshostedonmyownsite, Sep 2, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Just as a test, save the captchkey in plain text in the session.. so no md5($string) but just = $string;

    Then, in your validation function, output the input ($_POST['captchakey'] or whatever) and the $_SESSION['captchakey'] for debugging purposes.
     
    premiumscripts, Sep 2, 2009 IP