Validar Captcha antes del envio de formulario

  • Autor Autor josemanuelprz24
  • Fecha de inicio Fecha de inicio
J

josemanuelprz24

Beta
¡Usuario con pocos negocios! ¡Utiliza siempre saldo de Forobeta!
Hola muy buenos días.

Coloque un antispam en un formulario, el problema es que el captcha no se valida, el formulario se envía siempre no importa si escribiste el código antispam bien o mal.

Yo creo que son las condiciones que están fallando, no se mucho de PHP, soy nuevo, anexo el código del procesamiento

1 - Este es el input del captcha, junto con su imagen

HTML:
<input name="captcha" type="text" class="code" required style="border:1px solid #cecece;border-radius:5px;">
<img src="../contacto/pagina-shopper/captcha.php" width="100" height="50" />

2 - Este es el código del captcha

PHP:
<?php

// Start the session so we can store our generated key inside it for later retrieval

session_start( );

// Set to whatever size you want, or randomize for more security

$captchaTextSize = 7;

do {

    // Generate a random string and encrypt it with md5

    $md5Hash = md5( microtime( ) * mktime( ) );

    // Remove any hard to distinguish characters from our hash

    preg_replace( '([1aeilou0])', "", $md5Hash );

} while( strlen( $md5Hash ) < $captchaTextSize );

// we need only 7 characters for this captcha

$key = substr( $md5Hash, 0, $captchaTextSize );

// Add the newly generated key to the session. Note, it is encrypted.

$_SESSION['key'] = md5( $key );

// grab the base image from our pre-generated captcha image background

$captchaImage = imagecreatefrompng( "http://forobeta.com/images/captcha.png" );

/* 

Select a color for the text. Since our background is an aqua/greenish color, we choose a text color that will stand out, but not completely. A slightly darker green in our case.

*/ 

$textColor = imagecolorallocate( $captchaImage, 31, 118, 92 );

/* 

Select a color for the random lines we want to draw on top of the image, in this case, we are going to use another shade of green/blue

*/

$lineColor = imagecolorallocate( $captchaImage, 15, 103, 103 );

// get the size parameters of our image

$imageInfo = getimagesize( "http://forobeta.com/images/captcha.png" );

// decide how many lines you want to draw

$linesToDraw = 10;

// Add the lines randomly to the image

for( $i = 0; $i < $linesToDraw; $i++ )  {

	// generate random start spots and end spots

    $xStart = mt_rand( 0, $imageInfo[ 0 ] );
    $xEnd = mt_rand( 0, $imageInfo[ 0 ] );

    // Draw the line to the captcha

    imageline( $captchaImage, $xStart, 0, $xEnd, $imageInfo[1], $lineColor );

}

/* 

Draw our randomly generated string to our captcha using the given true type font. In this case, I am using BitStream Vera Sans Bold, but you could modify it to any other font you wanted to use.

*/

imagettftext( $captchaImage, 20, 0, 35, 35, $textColor, "fonts/VeraBd.ttf", $key );

// Output the image to the browser, header settings prevent caching

header ( "Content-type: image/png" );

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Fri, 19 Jan 1994 05:00:00 GMT");
header("Pragma: no-cache");

imagepng( $captchaImage );

?>

3 - Este es el código del procesamiento

PHP:
<?php
	include 'validar.php';
    include 'config.php';
    $nombre     =   $_POST['nombre']; 
	$correo    =   $_POST['correo'];
	$telefono    =   $_POST['telefono'];
    $mensaje  =   $_POST['mensaje'];
	$subject  =  "Contacto Arquark";
	$UN_SALTO =  "\r\n"; 
	$message  =  "Nombre: ". $nombre . $UN_SALTO  ."Correo: ".$correo . $UN_SALTO. "Telefono: " . $telefono. $UN_SALTO  ."Mensaje: ".$mensaje. $UN_SALTO .'Este Correo Fue Enviado desde la pagina de "Personal Shopper" ';
	
function limpiarString($string) 
   {
      $string = strip_tags($string);
      $string = htmlentities($string);
      return stripslashes($string);  

   }


if(mail($email_to, $subject, $message, $headers)){
      die ('');      
    }else{
        die ('Ha ocurrido un error por favor intentelo más adelante, gracias');    
    }



?>

4 - y Finalmente este es el código para validar el capcha

PHP:
<?php

session_start( ); // allows us to retrieve our key form the session

/* 

First encrypt the key passed by the form, then compare it to the already encrypted key we have stored inside our session variable

*/

if( md5( $_POST[ 'code' ] ) != $_SESSION[ 'key' ] ) {

       echo "El codigo de seguridad es incorrecto, porfavor vuelva a intentarlo";

} else {

       echo "Success, you ented the correct code, rock and roll...";

}

?>

Alguien sabe en que paso me equivoque, de antemano muchas gracias.

Un Saludo! :encouragement:
 
Última edición:
en donde verificas los valores mandalos primero con un echo a ver que valores te traen
 
if( md5( $_POST[ 'code' ] ) != $_SESSION[ 'key' ] )
quita el if
pon
echo md5( $_POST[ 'code' ] ) ." ".,$_SESSION[ 'key' ];

y verificas los valores que devuelve

- - - Actualizado - - -

if( md5( $_POST[ 'code' ] ) != $_SESSION[ 'key' ] )
quita el if
pon
echo md5( $_POST[ 'code' ] ) ." ".,$_SESSION[ 'key' ];

y verificas los valores que devuelve
 
Ya le quite la condición y lo englobe solo en un echo, como se indica.

Pero de entrada tengo un error de Sintaxis

PHP:
echo md5( $_POST[ 'code' ] ) ." ".,$_SESSION[ 'key' ];
 
Prueba con 2 echo uno para cada valor
 
Por que utilizas funciones como imagecreatefrompng para crear un captcha? Ese tipo de captchas hacen una función muy muy básica, te recomiendo reCaptcha de google y matas 2 pájaros de un tiro aparte que implementarlo es muy fácil.
 
Atrás
Arriba