PHP Captcha without session

后端 未结 13 1701
傲寒
傲寒 2021-01-04 13:51

Ok, here is an issue: in the project i\'m working on, we can\'t rely on server-side sessions for any functionality.

The problem is that common captcha solutions fro

13条回答
  •  不知归路
    2021-01-04 14:21

    Form with validation:

    $errorsucc = '';
    
    if (isset($_POST["captcha_check"])) {
    
        $code = str_decrypt($_POST["captcha_check"]);   
    
        if (empty($_POST['captcha_code'])) { 
            $errorsucc = '

    Please Enter the security code.

    '; } elseif(!( $code == $_POST['captcha_code'] && !empty($code) )) { $errorsucc = '

    Incorrect Code Entered.

    '; } else { $errorsucc = '

    Nice, you entered the correct code.

    '; } } $captcha = new CaptchaCode(); $code = str_encrypt($captcha->generateCode(6)); ?> Sessionless Captcha
    Security Code:
    Enter Code:

    Generate images just like any other captcha:

    /* font size will be 75% of the image height */
        $font_size = $height * 0.75;
        $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
        /* set the colours */
        $background_color = imagecolorallocate($image, 255, 255, 255);
        $text_color = imagecolorallocate($image, 0, 26, 26);
        $noise_color = imagecolorallocate($image, 25, 89, 89);
        /* generate random dots in background */
        for( $i=0; $i<($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for( $i=0; $i<($width*$height)/150; $i++ ) {
            imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
        }
        /* create textbox and add text */
        $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
    

    Download the demo files from this link: Create a Sessionless Captcha in PHP

提交回复
热议问题