在PHP / GD库中创建自定义Captcha

时间:2014-02-06 21:17:01

标签: php jquery gd captcha

如何使用PHP和GD库创建与此相同的验证码?

来源:http://www.aphrodite-agency.com/assets/captcha/captcha.php

圆圈中只有字母或数字有效...

index.php:

<?php
 session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Demo captcha</title>
  </head>
  <body>
    <form method="POST" action="">
      <h3>Quel est ce chiffre ?</h3>
      <img src="captcha.php" /><br />
      <input type="text" name="captcha" style="width:70px"/><br />
      <input type="submit" />
    </form>
<?php
 if($_POST['captcha']){
  if($_POST['captcha']==$_SESSION['captcha']) echo '<h3 style="color:green">Bingo !</h3>';
  else echo '<h3 style="color:red">Oups !</h3>';
 }
?>
  </body>
</html>

captcha.php:

<?php
  session_start();
  $_SESSION['captcha'] = rand(1000,9999);

 $img = imagecreatetruecolor(70, 30);

 $fill_color=imagecolorallocate($img,255,255,255);
 imagefilledrectangle($img, 0, 0, 70, 30, $fill_color);
 $text_color=imagecolorallocate($img,10,10,10);
 $font = './28DaysLater.ttf';
 imagettftext($img, 23, 0, 5,30, $text_color, $font, $_SESSION['captcha']);

 header("Content-type: image/jpeg");
 imagejpeg($img);
 imagedestroy($img);
?>

1 个答案:

答案 0 :(得分:0)

尝试使用 reCAPTCHA 在某些托管服务器中,基于GD的验证码不起作用。我经历过这个。 它可以与GD库一起使用。 它从外部服务加载验证码图像,并使用公钥加密验证。 所以内部生成验证码图像。 非常好用。

<强> E.G:

前端:

<html>
    <body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
      <!-- your HTML content -->

      <form method="post" action="verify.php">
        <?php
          require_once('recaptchalib.php');
          $publickey = "your_public_key"; // you got this from the signup page
          echo recaptcha_get_html($publickey);
        ?>
        <input type="submit" />
      </form>

      <!-- more of your HTML content -->
    </body>
  </html>

后端验证:

<?php
  require_once('recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
    // Your code here to handle a successful verification
  }
  ?>

了解更多信息请访问:https://developers.google.com/recaptcha/docs/php