Validate captcha with PHP

5

I have a captcha in a form where an image with 5 randomly generated values is displayed. How do I validate the captcha and only send the contact if the value entered in the input is equal to the one generated by the image?

Excerpt from the form that has the captcha:

<div class="col one-fourth" style="padding: 0 3px;">
    <img src="captcha.php"/>
</div>
<div class="col one-fourth" style="padding: 0 3px;">
    <input type="text" name="captcha" id="captcha" placeholder="Digite o código ao lado" class="campos_form" maxlength="5" required/>
</div>

This is the file I call that generates the image with the captcha:

<?php
session_start();
$codigoCaptcha = substr(md5( time()) ,0,5);
$_SESSION['captcha'] = $codigoCaptcha;

$imagemCaptcha = imagecreatefrompng("imagens/fundocaptcha.png");
$fonteCaptcha = imageloadfont("anonymous.gdf");
$corCaptcha = imagecolorallocate($imagemCaptcha,46,139,87);

imagestring($imagemCaptcha,$fonteCaptcha,15,5,$codigoCaptcha,$corCaptcha);
header("Content-type: image/png");
imagepng($imagemCaptcha);
imagedestroy($imagemCaptcha);
?>

How do I verify that the user has entered correctly? Can I use $_SESSION['captcha'] to compare the value? And how do I get the value of input ?

    
asked by anonymous 21.09.2015 / 20:42

1 answer

3

Hello,

Yes, you can capture the value of the input using

// pode ser feito assim...
$captchaEnviado = $_POST['captcha'];

//ou assim... que é mais seguro...
$captchaEnviado = filter_input(INPUT_POST, 'captcha', FILTER_SANITIZE_STRING);

if($captchaEnviado == $_SESSION['captcha'] ){
  //ok... continua...
}
else{
  //valor errado... trata como achar que deve....
}

More infos about filter_input here

and as mentioned this right here in SO

    
21.09.2015 / 20:53