验证simple-php-captcha()输入

时间:2018-07-20 10:31:19

标签: php variables captcha verification

POST表单工作正常,所有数据均已正确提交,$captcha_code返回正确的输出,$captcha也是如此。但是,当我检查$captcha == $captcha_code是否总是返回失败时。有人可以解释为什么会这样吗?

include 'inc/simple-php-captcha/simple-php-captcha.php';
$_SESSION['captcha'] = simple_php_captcha();
$captcha_code = $_SESSION['captcha']['code'];

if(isset($_POST['register'])) {
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = $_POST['password'];
  $cpassword = $_POST['cpassword'];
  $captcha = $_POST['captcha'];

  if($captcha == $captcha_code) {
    echo 'captcha success';
  } else {
    echo 'captcha failure';
  }
}

1 个答案:

答案 0 :(得分:0)

您需要先在login.php中生成验证码

login-form.php

<?php
// start session and generate captcha and it's image
session_start();
include 'inc/simple-php-captcha/simple-php-captcha.php';
$_SESSION['captcha'] = simple_php_captcha();

// render the form
?>

<input type="text" name="email">
<input type="text" name="password">
..
..
<input type="text" name="captcha">
<img src="<?php $_SESSION['captcha']['image_src']; ?>">
<input type="submit">

login-submit.php

$captcha_code = $_SESSION['captcha']['code']; //retrive what code was generated before

if(isset($_POST['register'])) {
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = $_POST['password'];
  $cpassword = $_POST['cpassword'];
  $captcha = $_POST['captcha'];

  if($captcha == $captcha_code) {    // try matching
    echo 'captcha success';
  } else {
    echo 'capture failure';
  }
}