Validate captcha with PHP

Asked

Viewed 780 times

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 input value 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 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 check if the user entered correctly? I can use the $_SESSION['captcha'] to compare the value? And how do I capture the value of input?

  • Hi, @PHP, you don’t need to tag the title, only if it’s organic. Usually it is better to describe the problem, the site’s regulars already filter the questions they want to answer using the tag system that [pt.so] offers.

1 answer

3


Hello,

can yes, capture the input value 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 information on the filter_input here

and as mentioned in this right here in the O.R.

  • Here: $captchaEnviado = $_POST['captcha']; can I declare this in the same file in the form? Or I need to pass via POST to another page?

  • @Phpdeveloper vc can do both modes, if the post is done the variable will be there, but it is important that you receive the parameter (I still state that using filter_input for security, I left the two methods for example). Remember to validate if it has already been used to avoid errors in your code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.