Search code examples
phpvariablescaptchaverification

Verifying simple-php-captcha() input


The POST form works fine and all the data is submitted properly, $captcha_code is returning the correct output and so is $captcha. However, when I check if $captcha == $captcha_code it always returns failure. Can someone please explain as to why this happens?

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';
  }
}

Solution

  • You need to generate the captcha before itself in 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';
      }
    }