PHP:Captcha验证码工作不正常


PHP : Captcha verification code not working properly;

我正在创建一个非常简单的Captcha验证过程。

(当用户尝试登录我的网站3次,但没有成功时,他会被重定向到Captcha页面(Captcha.php(,以验证他不是垃圾邮件机器人(

Captcha值本身是由一串字母和数字随机生成的。总共6位数字。

然后,我将这个值与用户在文本框中输入的值进行比较。如果值匹配,则用户可以继续。如果没有,页面将重新加载,显示一条错误消息,并生成一个新的captcha。

非常简单。没有javascript,没有ajax。

除了一件事:如果用户提供了正确的值,则Captcha不会重定向。

相反,它每次都会给出错误消息。

  <?php session_start();
   include 'database_connect.php';
   function getRandomString($length)  {
   $validCharacters =  
   "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    $validCharNumber = strlen($validCharacters);
    $result = "";
    for ($i = 0; $i < $length; $i++) {
    $index = mt_rand(0, $validCharNumber - 1);
    $result .= $validCharacters[$index];
    }
    return $result; }
    $captcha_value = getRandomString(6);
    ?>
   <!DOCTYPE html>
   <html>
   <head>
        <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
        <META HTTP-EQUIV="Cache-Control" CONTENT="no-store">
        <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
        <META HTTP-EQUIV="Expires" CONTENT="0">
        <META CHARSET="UTF-8">      
        <title>Captcha Test</title>         
  </head>
 <body>
    <fieldset><legend>CAPTCHA :</legend>
     <?php 
            if (isset($_POST['submit'])) {
                $post_captcha = $_POST['captcha'];
                if ($post_captcha == $captcha_value) {
                $clear_failed_logins =  mysqli_query($conn,("Delete FROM 
                                        login_attempts where login = 
                                        '$_POST[login]'")) 
                                        or die(mysqli_error($conn)); 
                header ("Location: /example.com/login.php");    
                exit();     
            }
            else {
            echo "<p style='color:red; font-weight:bold;'>The value you  
                   entered is not correct! Please try again.</p>";
             }
          }
        ?> 
        <p>Please input the characters you see into the text-box below :</p>
        <p>  <?= $captcha_value ?> </p>
        <form method="POST" action="captcha.php">
        <input type="text" name="captcha" id="captcha" size=10 
                     autocomplete="off" required><br><br><br> 
        <input type="submit" name="submit" id="submit" value="SUBMIT"> 
        </form>
    </fieldset> 

在向用户输出内容后,您无法在php中使用标头进行重定向,因此在输出内容之前,请将if-else块移到页面顶部。如果你想在这个位置重定向,请尝试元刷新

 <meta http-equiv="refresh" content="0; URL=http://www.domain.com">

此外,您应该将captcha值存储在表单中,因为每次刷新页面时都会重新生成它(因此在表单提交后(,我建议您使用reCaptcha进行尝试,这很容易实现,也更安全