如果失败则刷新验证码

时间:2016-05-12 15:07:57

标签: php captcha

我在php中创建了自定义验证码。我希望验证失败时刷新验证码上的文本,以便用户不必再次填写表单。我怎么能这样做?

<?php
    if(!session_id() || session_id() == ''){
        session_start();
    }

    $captcha = "";

    for ($i=0; $i < 5; $i++) {

        $captcha .= chr(rand(97,122));

    }

    $_SESSION['captcha_code'] = $captcha;

    $dir = 'fonts/';

    $image = imagecreatetruecolor(170,60);
    $black = imagecolorallocate($image, 0, 0, 0);
    $color = imagecolorallocate($image, 255, 10, 10);
    $white = imagecolorallocate($image, 255, 255, 255);

    imagefilledrectangle($image , 0 , 0 , 200 , 100 , $white);
    imagettftext($image, 30, 5 , 10 , 40 , $color , 'fonts/MacyandKaraFont.ttf' , $_SESSION['captcha_code']);

    header("Content-type: image/png");
    imagepng($image);
    // session_destroy();

 ?>

验证码的Html代码

 <div class="col-md-3">
       <img src="captcha.php" alt="" /> <br/>
             <div class="form-group floating-label-form-group">
                 <label>Enter code as seen above</label>
           <input type="text" name="code" Placeholder="Enter code as see above" class="form-control">
               <p class="help-block text-danger"></p>
         </div>
    </div>

<?php
    if (isset($_POST['statement-submit'])) {

            // echo $_SESSION['captcha_code'];
            // echo $_POST['code'];
            $code = htmlentities(strip_tags(trim($_POST['code'])));

            if ($_SESSION['captcha_code'] === $code) {
?>

1 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用AJAX。以下是我认为可能派上用场的东西......

<强> JAVASCRIPT:

   // 
   // PULL-IN JQUERY FROM THE CDN.
   // IF YOU ALREADY HAVE IT LOCALLY, CHANGE THE SRC ATTRIBUTE.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script type="text/javascript">
        (function ($) {
            $(document).ready(function(e) {
                // ASSUMING THAT THE CAPTCHA FIELD'S CLASS IS "captcha_field"
                // YOU CAN JUST USE JAVASCRIPT'S ON-BLUR EVENT TO TRIGGER THE SENDING OF A REQUEST TO THE PHP SCRIPT LIKES BELOW
                // BUT FIRST WE DECLARE A VARIABLE TO HOLD THE CAPTCHA FIELD'S JQUERY OBJECT...
                var captchaField    = $(".captcha_field");      <== CHANGE TO THE APPROPRIATE CLASS OR ID 

                // SET UP THE EVENT HANDLER FOR THE ON-BLUR AS MENTIONED ABOVE...
                captchaField.on("blur", function(evt){              
                    $.ajax({
                        url: 'ajax_helper.php',     // <== POINTS TO THE VALID URL OF THE AJAX HELPER... DECIDE FOR YOURSELF...
                        dataType: "json",
                        cache: false,
                        type: "POST",
                        data: ({
                            'captcha_code'  : captchaField.val()    // <== ASSUMES THAT THE CAPTCHA FIELD HAS A CLASS CALLED captcha_field 
                        }),

                        //HANDLE THE SUCCESS CASE FOR THE AJAX CALL
                        success: function (data, textStatus, jqXHR) {
                            if(data){
                                // CHECK IF THE THERE WAS AN ERROR WITH THE CAPTCHA VALIDATION IN THE PHP SCRIPT 
                                if(data.error && data.error != null){
                                    // DISPLAY A WARNING MESSAGE TO THE USER TO INFORM THEM OF THE ERROR...
                                    // HERE WE USE A SIMPLE ALERT BUT YOU CAN IMPLEMENT YOUR FANCY UI...
                                    alert(data.error);
                                }else {
                                    // IF EVERYTHING WORKS FINE; YOU CAN DO WHATEVER YOU WISH HERE...
                                    // PERHAPS POST THE FORM OR JUST IGNORE THIS CLAUSE.
                                }
                            }
                        },

                        //HANDLE THE FAILURE CASE FOR THE AJAX CALL
                        error: function (jqXHR, textStatus, errorThrown) {
                            console.log('The following error occured: ' + textStatus, errorThrown);
                        },

                        //HANDLE THE EVENT-COMPLETE CASE FOR THE AJAX CALL
                        complete: function (jqXHR, textStatus) {
                        }
                    });
                });
            });
        })(jQuery);
    </script>

创建一个新的PHP文件(无论你喜欢什么,我都称它为 ajax_helper.php ,为简单起见。这个文件将处理你的AJAX请求。

PHP:

    <?php
        /**
         * 
         * AJAX HELPER
         * Filename: ajax_helper.php
         * 
         */ 

        // CHECK TO SEE THAT YOUR AJAX CALL POSTED THE captcha_code DATA TO THE AJAX HELPER SCRIPT
        if( isset($_POST['captcha_code'])  && $_POST['captcha_code'] ){
            $captcha_code       = $_POST['captcha_code'];
            // NOW, DO YOUR PROCESSING...
            // USE YOUR CAPTCHA'S LOGIC TO DETERMINE WHETHER THE CAPTCHA WAS RIGHT OR NOT
            // IN THE END YOU'D HAVE A CONDITIONAL LOGIC LIKE BELOW:

            // COMPARE THE VALUE OF THE $captcha_code TO THE VALUE STORED IN THE SESSION                
            if($captcha_code == $_SESSION['captcha_code']){
                $ajaxPayload    = array(
                    "error"     => null,
                );
            }else{
                $ajaxPayload    = array(
                    "error"     => "The entered Captcha is invalid. Please, try again.",
                );          
            }

            die( json_encode($ajaxPayload));
        }else{
            $ajaxPayload    = array(
                "error"     => "You haven't entered the Captcha. Please, enter the Capture Code.",
            ); 
            die( json_encode($ajaxPayload));

        }