Validate captcha before submitting Form
I need a very simple captcha, but that can be validated before the form is submitted, How can I do that?
I currently use this:
Index.html
<form method="post" action="valida.php" id="form" name="form">
<!-- campos -->
<div class="form-group">
<label>Captcha*:<img src="captcha.php?l=105&a=35&tf=15&ql=5"></label>
<input type="text" name="palavra" id="palavra" class="form-control input-lg" required>
</div>
</form>
Captcha.php
<?php
session_start();
header("Content-type: image/jpeg");
function captcha($largura,$altura,$tamanho_fonte,$quantidade_letras){
$imagem = imagecreate($largura,$altura);
$fonte = "verdana.ttf";
$preto = imagecolorallocate($imagem,243,243,243);
$branco = imagecolorallocate($imagem,0,151,182);
$palavra = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVYXWZ23456789"),0,($quantidade_letras));
$_SESSION["palavra"] = $palavra;
for($i = 1; $i <= $quantidade_letras; $i++){
imagettftext($imagem,$tamanho_fonte,rand(0,0),($tamanho_fonte*$i),($tamanho_fonte + 10),$branco,$fonte,substr($palavra,($i-1),1));
}
imagejpeg($imagem);
imagedestroy($imagem);
}
$largura = $_GET["l"];
$altura = $_GET["a"];
$tamanho_fonte = $_GET["tf"];
$quantidade_letras = $_GET["ql"];
captcha($largura,$altura,$tamanho_fonte,$quantidade_letras);
?>
Validate.php
if ($_POST["palavra"] == $_SESSION["palavra"]) {
//...
}
But I don't know how to check if the captcha was filled correctly before submitting the form.
2 answers
In the method or function that handles Form Submission, you can query Captcha
via Ajax
, so if it'S OK, you can submit the remaining form data.
Well, I got it as follows:
In my captcha input I call a function Cap()
:
<form method="post" action="#" id="form" name="form">
<!-- campos -->
<div class="form-group">
<label>Captcha*:<img src="captcha.php?l=105&a=35&tf=15&ql=5"></label>
<input type="text" name="palavra" id="palavra" class="form-control input-lg" onkeyup="Cap();" required>
</div>
</form>
The function Cap()
in turn sends the form via ajax to check the captcha and enable or disable the form submit button according to the response.:
<script>
function Cap(){
var form = $("#form").serializeArray();
var url = "valida.php";
if($("#palavra").val().length){
$.post(url, form, function(data){
if(data == 'error'){
$("#submit").prop("disabled", true);
}else{
$("#submit").prop("disabled", false);
}
});
}else{
$("submit").prop("disabled", true);
}
}
</script>
Or validate.php looked like this:
<?php
session_start();
if ($_POST["palavra"] == $_SESSION["palavra"]) {
echo "success";
} else {
echo "error";
}
?>
Or captcha.php remained the same. I do not know if it is the best way to do it, but it is working well and supplying the current need.