Foros del Web » Programando para Internet » PHP »

Validación recaptcha

Estas en el tema de Validación recaptcha en el foro de PHP en Foros del Web. Tengo el siguiente código, el captcha me sale correctamente, pero no se donde y como poner la validación. Ahora mismo ignora por completo el captcha, ...
  #1 (permalink)  
Antiguo 22/08/2014, 14:02
 
Fecha de Ingreso: mayo-2014
Ubicación: Valencia
Mensajes: 63
Antigüedad: 9 años, 11 meses
Puntos: 0
Validación recaptcha

Tengo el siguiente código, el captcha me sale correctamente, pero no se donde y como poner la validación. Ahora mismo ignora por completo el captcha, vamos, me sale pero da igual que lo rellene bien, mal o no lo rellene, el formulario se envía igualmente.

¿Alguna ayuda?

Pongo el código en varios mensajes, que no me deja en uno solo.

Gracias.

Código PHP:
<?php require_once('Connections/conexion.php'); ?>
<?php 
require_once('includes/funciones.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  if (
PHP_VERSION 6) {
    
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

mysql_select_db($database_conexion$conexion);
//$query_DatosCentros = "SELECT * FROM tblcentro ORDER BY tblcentro.refProvincia ASC,  tblcentro.strLocalidad ASC , strNombre ASC";
$query_DatosCentros "SELECT tblcentro.*,tblprovincias.provincia, tblprovincias.id FROM
tblcentro
Inner Join tblprovincias ON tblcentro.refProvincia = tblprovincias.id ORDER BY tblprovincias.provincia ASC, tblcentro.strLocalidad ASC, tblcentro.strNombre ASC"
;
$DatosCentros mysql_query($query_DatosCentros$conexion) or die(mysql_error());
$row_DatosCentros mysql_fetch_assoc($DatosCentros);
$totalRows_DatosCentros mysql_num_rows($DatosCentros);

$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "formulario")) {
  
$insertSQL sprintf("INSERT INTO tblusuarios (strNombre, strApellidos, strEspecialidad, intCentro,  strEmail, intTelefono, strMensaje, intOrigen) VALUES (%s, %s, %s, %s, %s, %s, %s, 0)",
                       
GetSQLValueString($_POST['strNombre'], "text"),
                       
GetSQLValueString($_POST['strApellidos'], "text"),
                       
GetSQLValueString($_POST['strEspecialidad'], "text"),
                       
GetSQLValueString($_POST['intCentro'], "int"),        
                       
GetSQLValueString($_POST['strEmail'], "text"),
                       
GetSQLValueString($_POST['intTelefono'], "text"),
                       
GetSQLValueString($_POST['strMensaje'], "text"));

  
mysql_select_db($database_conexion$conexion);
  
$Result1 mysql_query($insertSQL$conexion) or die(mysql_error());

  
$insertGoTo "profesores-registro-ok.php";
  
/*if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }*/

  
$query_DatosCentros2 "SELECT strNombre, strLocalidad, tblprovincias.provincia, tblprovincias.id FROM tblcentro Inner Join tblprovincias ON tblcentro.refProvincia = tblprovincias.id WHERE intCentro = '" $_POST['intCentro'] . "'";
  
$DatosCentros2 mysql_query($query_DatosCentros2$conexion) or die(mysql_error());
  
$row_DatosCentros2 mysql_fetch_assoc($DatosCentros2);
  
$totalRows_DatosCentros2 mysql_num_rows($DatosCentros2);

  
header(sprintf("Location: %s"$insertGoTo));
    
$asunto 'Formulario de Contacto Enviado desde profesores registrados';
    
$destinatario '[email protected]';
    
$mensaje "Hola admin,<br />";
    
$mensaje .= "se ha enviado un formulario de contacto desde profesores resgistrados con lo siguientes datos:<br /><br />";    $mensaje .= "- Nombre: ".$_POST['strNombre']."<br />";
    
$mensaje .= "- Apellidos: ".$_POST['strApellidos']."<br />";
    
$mensaje .= "- Especialidad: ".$_POST['strEspecialidad']."<br />";
    
$mensaje .= "- Provincia: ".$row_DatosCentros2['provincia'] ."<br />"
    
$mensaje .= "- Localidad: ".$row_DatosCentros2['strLocalidad'] ."<br />";
    
$mensaje .= "- Centro: ".$row_DatosCentros2['strNombre'] ."<br />";
    
$mensaje .= "- Telefono: ".$_POST['intTelefono']."<br />";
    
$mensaje .= "- Email: ".$_POST['strEmail']."<br />";
    
$mensaje .= "- Mensaje: ".nl2br($_POST['strMensaje'])."<br /><br />";    
    
EnviarCorreoHTML($destinatario,$asunto,utf8_decode($mensaje));
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  
session_start();
}

$loginFormAction $_SERVER['PHP_SELF'];
if (isset(
$_GET['accesscheck'])) {
  
$_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset(
$_POST['emailacceso'])) {
  
$loginUsername=$_POST['emailacceso'];
  
$password=$_POST['passwordacceso'];
  
$MM_fldUserAuthorization "intNivelAcceso";
  
$MM_redirectLoginSuccess "archivos-listado.php"/*"profesores-registrados.php";*/
  
$MM_redirectLoginFailed "profesores-acceso-nok.php";
  
$MM_redirecttoReferrer false;
  
mysql_select_db($database_conexion$conexion);
      
  
$LoginRS__query=sprintf("SELECT  intId, strNombre, strEmail, strPassword, intNivelAcceso FROM tblusuarios WHERE strEmail=%s AND strPassword=md5(%s) && intActivo=1",
  
GetSQLValueString($loginUsername"text"), GetSQLValueString($password"text")); 
   
  
$LoginRS mysql_query($LoginRS__query$conexion) or die(mysql_error());
  
$row_LoginRS mysql_fetch_assoc($LoginRS);
  
$loginFoundUser mysql_num_rows($LoginRS);
  if (
$loginFoundUser) {
    
    
$loginStrGroup  mysql_result($LoginRS,0,'intNivelAcceso');
    
    if (
PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
    
//declare two session variables and assign them
    
$_SESSION['MM_Username'] = $loginUsername;/* EMail*/
    
$_SESSION['MM_UserGroup'] = $loginStrGroup;/* Nivel aacceso  */          
    
$_SESSION['MM_Nombre'] = $row_LoginRS['strNombre'];/*Nombre Usuario */     
    
$_SESSION['MM_Id'] = $row_LoginRS['intId'];/*Id Usuario */         
    /*echo $_SESSION['MM_Username'];
    echo $_SESSION['MM_UserGroup'];
    echo $_SESSION['MM_Nombre'];*/

    
if (isset($_SESSION['PrevUrl']) && false) {
      
$MM_redirectLoginSuccess $_SESSION['PrevUrl'];    
    }
    
header("Location: " $MM_redirectLoginSuccess );
  }
  else {
    
header("Location: "$MM_redirectLoginFailed );
  }
}
?>
<!DOCTYPE html>
<html lang="es"><!-- InstanceBegin template="/Templates/Principal.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<!-- InstanceBeginEditable name="doctitle" -->
<title>xxx.es</title>
<meta name="description" content="">
<meta name="robots" content="index, follow">
<!-- InstanceEndEditable -->
<meta charset="utf-8">
<?php include("includes/precabecera.php"); ?>

<!-- InstanceBeginEditable name="head" -->
<!-- InstanceEndEditable -->
</head>
<body>
<!-- InstanceBeginEditable name="EditRegion3" -->
<?php $menuseleccionado 6;?>
<section class="bg1">
  <!--==============================header=================================-->
  <header id="header">
    <div class="container_12">
      <?php include("includes/cabecera.php"); ?>
      <?php //include("includes/slider.php"); ?>
      <?php include("includes/menu.php"); ?>
    </div>
  </header>
  #2 (permalink)  
Antiguo 22/08/2014, 14:03
 
Fecha de Ingreso: mayo-2014
Ubicación: Valencia
Mensajes: 63
Antigüedad: 9 años, 11 meses
Puntos: 0
Respuesta: Validacion recaptcha

Código PHP:
 <!--===================content====================-->
  <div id="content">
    <div class="container_12">
        <div class="row">
            <div class="grid_4">
            <!---->
            <!---->
            <!-- ACCESO-->
            <!---->
            <?php if( !isset($_SESSION['MM_Id']) ){ ?>
            <h3 class="mrg22 pad3">Acceso</h3>
            
            <p class="p4">Si ya es un usuario registrado y dispone de contraseña,
          acceda al sitio con email y contraseña</p>
            <?php /*?><p class="p4">SuperAdmin: [email protected]  pass:12345</p>
            <p class="p4">Normal User: [email protected]  pass:111</p><?php */
?>

            <form action="<?php echo $loginFormAction?>"  method="POST" name="formularioacceso" id="formacceso">
                 
                  
                   
            <label class="email">
                                  <input class="forminput" name="emailacceso" type="text" id="emailacceso" placeholder="E-mail *:" size="40"  onclick="javascript: borraremailacceso();"/>
                                            
            </label>
            <div id="erroremailacceso" class="ocultar texto-error">Debe ser un email válido</div>
            <br><br>
            <label class="password">
                                  <input class="forminput" name="passwordacceso" type="password" id="passwordacceso" placeholder="Contraseña *:" size="40" onclick="javascript: borrarpasswordacceso();"/>
                                           
            </label>
            <div id="errorpasswordacceso" class="ocultar texto-error">Campo Obligatorio</div>
             <br><br>
            <input class="iconomano" id="botonacceso" name="botonacceso" type="submit"  value="Acceder" onclick="javascript: return validaracceso();">
           
</form>
            <?php }?>
            <!---->
            <!---->
            <!---->
            <!---->
            <!---->
            <!---->
            <?php if( isset($_SESSION['MM_Id']) ){ ?>
            <h3 class="mrg22 pad3">Bienvenido, <?php echo $_SESSION['MM_Nombre']; ?></h3>
            
            <img src="images/iconos/download.png" width="20" height="20"> <a href="archivos-listado.php" class="a14">Lista de Archivos</a>
            <br><br><br>            
            <a id="botonsalir" href="profesores-salir.php">Salir</a>
            <?php  }?>
             <!---->
            <!---->
            <!---->
            <!---->
            <!---->
            <!---->
           
           
           
           
            <!---->
            <!---->
            <!---->
            <!---->
            <!---->
            <!---->
              <h3 class="mrg22 pad3">Contacto<br><br>
<img src="images/profesores-registrados.jpg" width="267" height="267"></h3>
                <div class="map">
                  <div>
                      <p class="p4">xxx</p>
                </div>
                    <address class="mb0">
                    <span class="p4">Horario:<br>
                    De 10 a 14 y de 16 a 18 horas.
                    </span>
                    </address>
                    <address class="mb0">
                    <p>&nbsp;</p>
                        <p>&nbsp;</p>
                        <p>&nbsp;</p>
                        <p>&nbsp;</p>
                        <p>&nbsp;</p>
                        <p>&nbsp;</p>
                        <p>&nbsp;</p>
                        <p>&nbsp;</p>
                    </address>
                </div>
            </div>
            <div class="grid_8">
                <h3 class="mrg22 pad3">Formulario</h3>
                <p class="p4">Los centros y profesores que realizan un seguimiento de nuestros libros en el aula pueden darse de alta en nuestra web y recibir algunos servicios adicionales:<br>
                  <br>
• Envío del solucionario de actividades y programación didáctica al correo electrónico.<br>
• Envío de los powers-points de las UD de FOL y de EIE. <br>
  • Envío de las actualizaciones de legislación laboral y empresarial que se vaya produciendo a lo largo del curso (para profesorado de FOL).
  <br>
  • Información sobre nuevos libros de texto de tu especialidad que se publiquen en la editorial.<br>


  <br>
  Para registrarte debes rellenar el siguiente formulario e indicar en qué centro eres docente. Realizaremos una llamada de comprobación al centro, para asegurarnos de enviar el material al profesorado que sigue nuestros libros de texto, y te daremos de alta.</p>
                <form method="POST" action="<?php echo $editFormAction?>" name="formulario" >    
                  <div class="success_wrapper">
                        <div id="mensajeregistroenviado" class="mensajeenviado ocultar">Formulario enviado correctamente, en breve nos pondremos en contacto con usted.</div>
                  </div>
                                         <br>Nombre:<br>
                      <input class="seleccion" id="nombreregistro" name="strNombre" type="text" placeholder="Nombre*:" onClick="javascript:  borrarnombre();"/>
                        <div id="errorregistronombre" class="ocultar texto-error">* Campo obligatorio</div>                        
   
   
                          <br><br>Apellidos:<br><input class="seleccion" id="apellidosregistro" name="strApellidos" type="text" placeholder="Apellidos*:" onClick="javascript:  borrarapellidos();" />
                     <div id="errorregistroapellidos" class="ocultar texto-error">* Campo obligatorio</div>
   
                      <br><br>Especialidad:<br><input class="seleccion" id="especialidadregistro" name="strEspecialidad" type="text" placeholder="Especialidad*:" onClick="javascript:  borrarespecialidad();" />
                   <div id="errorregistroespecialidad" class="ocultar texto-error">* Campo obligatorio</div>
  #3 (permalink)  
Antiguo 22/08/2014, 14:04
 
Fecha de Ingreso: mayo-2014
Ubicación: Valencia
Mensajes: 63
Antigüedad: 9 años, 11 meses
Puntos: 0
Respuesta: Validacion recaptcha

Código PHP:
                     <br><br>Centro: <br>
                
                     <select name="intCentro" id="intCentro" class="seleccion">
                       <?php
do {  
?>
                       <option value="<?php echo  $row_DatosCentros['intCentro']?>"><?php echo   $row_DatosCentros['provincia']." - "$row_DatosCentros['strLocalidad']." - ".$row_DatosCentros['strNombre']?></option>
                       <?php
} while ($row_DatosCentros mysql_fetch_assoc($DatosCentros));
  
$rows mysql_num_rows($DatosCentros);
  if(
$rows 0) {
      
mysql_data_seek($DatosCentros0);
      
$row_DatosCentros mysql_fetch_assoc($DatosCentros);
  }
?>
                     </select>
                     <div id="errorregistrocentro" class="ocultar texto-error">* Campo obligatorio</div>
                  
              
                      <br><br>Email:<br><input class="seleccion" id="emailregistro" name="strEmail" type="text" placeholder="E-mail*:"/>
                    <div id="errorregistroemail" class="ocultar texto-error">* Debe ser un Email válido</div>
                    <div id="errorregistroemailduplicado" class="ocultar texto-error">* Esta dirección de correo ya está siendo usada por un usuario</div>
                   
             
                      <br><br>Teléfono: <br> <input class="seleccion" id="telefonoregistro" name="intTelefono" type="text" placeholder="Teléfono*:" onClick="javascript:  borrartelefono();" />
                    <div id="errorregistrotelefono" class="ocultar texto-error">* Debe ser un Teléfono válido</div>
               
                        <br><br>Mensaje:<br><textarea class="seleccionarea" id="mensajeregistro" name="strMensaje" placeholder="Mensaje:" rows="5" onClick="javascript:  borrarmensaje();"></textarea>
<div id="errorregistromensaje" class="ocultar texto-error">* Debe escribir un Mensaje</div>
<br><br>
</tr><tr>
<td>¿Es usted un humano?</td><td>
<?php

@require_once('recaptchalib.php');
// aquí se ponen las keys solicitadas
$publickey "6LcaDPkSAAAAAMoSV_IHMJOOrYsz5I0pkC1X59Aa";
$privatekey "6LcaDPkSAAAAAMY5uEnJvZLXm4PeqGng9hpRMasq";
$resp null$error null
if (
$_POST["submit"]) { 
$resp recaptcha_check_answer ($privatekey$_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); 

if (
$resp->is_valid) { 
$to="usted@sudominio"
$subject="Titulo de ejemplo";
$body=" Mensaje formulario: Nombre: " .$_POST["nombre"] . "\n Email: " .$_POST["email"] . "\n Mensaje: " .$_POST["mensaje"] . "\n"
/* enviando correo */ 
mail($to,$subject,$body); 
echo 
"Correo Enviado!"
exit(
1); 
} else { 
echo 
"Lo sentimos pero no ha colocado el texto correctamente! Intente nuevamente..."; } 


echo 
recaptcha_get_html($publickey$error); ?>   
                    
                    
                        <div class="clear"></div>
                        <div class="btns">
                            
                           <input id="botonalta" class="botton" type="submit" value="Aceptar" onClick="javascript: return validar();"><br>
<br>
<br>

                                           
                          
                        </div>
      

                    <input type="hidden" name="MM_insert" value="formulario">
                </form>
            </div>
        </div>
    </div>
  </div>
  <!--===================footer=====================-->
  <?php include("includes/footer.php"); ?>
</section>
<!-- InstanceEndEditable -->
</body>
<!-- InstanceEnd --></html>
<?php
mysql_free_result
($DatosCentros);
?>
<script type="text/javascript">    
    function validar(){        
        validado = true;        
        valor = document.getElementById("nombreregistro").value;        
        if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
            $('#errorregistronombre').show(1000);
              validado = false;
        } else {
            $('#errorregistronombre').hide(1000);            
        }
        
        valor = document.getElementById("apellidosregistro").value;        
        if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
            $('#errorregistroapellidos').show(1000);
              validado = false;
        } else {
            $('#errorregistroapellidos').hide(1000);            
        }    
        
        valor = document.getElementById("especialidadregistro").value;        
        if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
    
            $('#errorregistroespecialidad').show(1000);
              validado = false;
        } else {
            $('#errorregistroespecialidad').hide(1000);            
        }
            
/*        valor = document.getElementById("centroregistro").value;        
        if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
            $('#errorregistrocentro').show(1000);
              validado = false;
        } else {
            $('#errorregistrocentro').hide(1000);            
        }
        valor = document.getElementById("localidadcentroregistro").value;        
        if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
            $('#errorregistrolocalidadcentro').show(1000);
            $('#errorregistroemailduplicado').hide(1000);    
              validado = false;
        } else {
            $('#errorregistrolocalidadcentro').hide(1000);            
        }    */

        valor = document.getElementById("emailregistro").value;
        if( !(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(valor)) ) {
            $('#errorregistroemail').show(1000);
            validado = false;
        } else {
            $('#errorregistroemail').hide(1000);    
            <!---->
            <!---->
            <!---->
            <!---->
            valor = document.getElementById("emailregistro").value;
            $.ajax({
                            async: false,
                            type: "POST",
                            url:"includes/funciones-ajax.php",
                            data: 'stremailusuario='+valor+'&formid=1',
                            success: function(resp)
                            { 
                                    // El email de usuario no existe            
                                    if (resp==1){                                                    
                                                $('#errorregistroemailduplicado').hide(1000);                                                
                                        }
                                    // El email de usuario ya está en uso
                                    if (resp==0){

                                                $('#errorregistroemail').hide(1000);
                                                $('#errorregistroemailduplicado').show(1000);
                                                validado = false;
                                        }
                            }
        });
            
            
            
            <!---->
            <!---->
            <!---->
        }        
        
        valor = document.getElementById("telefonoregistro").value;
        if( !(/^\d{9}$/.test(valor)) ) {
            $('#errorregistrotelefono').show(1000);
            validado = false;            
        } else {
            $('#errorregistrotelefono').hide(1000);
            
            }
            
        valor = document.getElementById("mensajeregistro").value;        
        if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
            $('#errorregistromensaje').show(1000);
              validado = false;
        } else {
            $('#errorregistromensaje').hide(1000);            
        }    
    
    if (validado==false){return false;}            
    

    
    }
    </script>
    <script type="text/javascript">
    function limpiarformulario(){
    $('#errorregistronombre').hide(0);    
    document.formulario.nombreregistro.value="";
/*    $('#nombreregistro').attr('placeholder','Nombre*:');*/
    
    $('#errorregistroapellidos').hide(0);    
    document.formulario.apellidosregistro.value="";
/*    $('#apellidosregistro').attr('placeholder','Apellidos*:');*/
    
    $('#errorregistroespecialidad').hide(0);        
    document.formulario.especialidadregistro.value="";
/*    $('#especialidadregistro').attr('placeholder','Especialidad*:');*/
    
    $('#errorregistrocentro').hide(0);    
    document.formulario.centroregistro.value="";
/*    $('#centroregistro').attr('placeholder','Centro*:');*/
    
/*    $('#errorregistrolocalidadcentro').hide(0);    
    document.formulario.localidadcentroregistro.value="";
/*    $('#localidadcentroregistro').attr('placeholder','Localidad del Centro*:');*/*/
    
    $('#errorregistroemail').hide(0);
    $('#errorregistroemailduplicado').hide(0);        
    document.formulario.emailregistro.value="";
/*    $('#emailregistro').attr('placeholder','E-mail*:');*/

    $('#errorregistrotelefono').hide(0);
    document.formulario.telefonoregistro.value="";
/*    $('#telefonoregistro').attr('placeholder','Teléfono:');    */
    
    $('#errorregistromensaje').hide(0);    
    document.formulario.mensajeregistro.value="";
/*    $('#mensajeregistro').attr('placeholder','Mensaje:');    */
        }
    </script>
    

<script type="text/javascript">
function borrarnombre(){
    $('#errorregistronombre').hide(1000);
    }
function borrarapellidos(){
    $('#errorregistroapellidos').hide(1000);
    }
function borrarespecialidad(){
    $('#errorregistroespecialidad').hide(1000);
    }        
/*function borrarcentro(){
    $('#errorregistrocentro').hide(1000);
    }
function borrarlocalidadcentro(){
    $('#errorregistrolocalidadcentro').hide(1000);
    }*/
function borrartelefono(){
    $('#errorregistrotelefono').hide(1000);
    }    
function borrarmensaje(){    
    $('#errorregistromensaje').hide(1000);
    }
</script>
<script type="text/javascript">
/****************************************/
/* Validacion Acceso                    */
/*****************************************/
function validaracceso(){
    validado = true;
    valor = document.getElementById("passwordacceso").value;
    if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
            $('#errorpasswordacceso').show(1000);
              validado = false;
        }
    valor = document.getElementById("emailacceso").value;
    if( !(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(valor)) ) {
            $('#erroremailacceso').show(1000);
            validado = false;
        } 
    
if (validado == false) { return false;}    
}
function borrarpasswordacceso(){
    $('#errorpasswordacceso').hide(1000);
    }
function borraremailacceso(){
    $('#erroremailacceso').hide(1000);
    }
</script>
  #4 (permalink)  
Antiguo 22/08/2014, 19:45
 
Fecha de Ingreso: mayo-2014
Ubicación: Valencia
Mensajes: 63
Antigüedad: 9 años, 11 meses
Puntos: 0
Respuesta: Validacion recaptcha

Ya lo he solucionado de la siguiente forma...

Código:
<?php require_once('Connections/conexion.php'); ?>
<?php require_once('includes/funciones.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_conexion, $conexion);
//$query_DatosCentros = "SELECT * FROM tblcentro ORDER BY tblcentro.refProvincia ASC,  tblcentro.strLocalidad ASC , strNombre ASC";
$query_DatosCentros = "SELECT tblcentro.*,tblprovincias.provincia, tblprovincias.id FROM
tblcentro
Inner Join tblprovincias ON tblcentro.refProvincia = tblprovincias.id ORDER BY tblprovincias.provincia ASC, tblcentro.strLocalidad ASC, tblcentro.strNombre ASC";
$DatosCentros = mysql_query($query_DatosCentros, $conexion) or die(mysql_error());
$row_DatosCentros = mysql_fetch_assoc($DatosCentros);
$totalRows_DatosCentros = mysql_num_rows($DatosCentros);

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

require_once('recaptchalib.php');
 
// Get a key from http://recaptcha.net/api/getkey
$publickey = "XXX";
$privatekey = "XXX";
 
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
 
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);
 
        if ($resp->is_valid) {
			
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "formulario")) {
  $insertSQL = sprintf("INSERT INTO tblusuarios (strNombre, strApellidos, strEspecialidad, intCentro,  strEmail, intTelefono, strMensaje, intOrigen) VALUES (%s, %s, %s, %s, %s, %s, %s, 0)",
                       GetSQLValueString($_POST['strNombre'], "text"),
                       GetSQLValueString($_POST['strApellidos'], "text"),
                       GetSQLValueString($_POST['strEspecialidad'], "text"),
                       GetSQLValueString($_POST['intCentro'], "int"),        
                       GetSQLValueString($_POST['strEmail'], "text"),
                       GetSQLValueString($_POST['intTelefono'], "text"),
                       GetSQLValueString($_POST['strMensaje'], "text"));

  mysql_select_db($database_conexion, $conexion);
  $Result1 = mysql_query($insertSQL, $conexion) or die(mysql_error());

  $insertGoTo = "profesores-registro-ok.php";
  /*if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }*/

  $query_DatosCentros2 = "SELECT strNombre, strLocalidad, tblprovincias.provincia, tblprovincias.id FROM tblcentro Inner Join tblprovincias ON tblcentro.refProvincia = tblprovincias.id WHERE intCentro = '" . $_POST['intCentro'] . "'";
  $DatosCentros2 = mysql_query($query_DatosCentros2, $conexion) or die(mysql_error());
  $row_DatosCentros2 = mysql_fetch_assoc($DatosCentros2);
  $totalRows_DatosCentros2 = mysql_num_rows($DatosCentros2);

  header(sprintf("Location: %s", $insertGoTo));
	$asunto = 'Formulario de Contacto Enviado desde profesores registrados';
	$destinatario = '[email protected]';
    $mensaje = "Hola admin,<br />";
    $mensaje .= "se ha enviado un formulario de contacto desde profesores resgistrados con lo siguientes datos:<br /><br />";    $mensaje .= "- Nombre: ".$_POST['strNombre']."<br />";
    $mensaje .= "- Apellidos: ".$_POST['strApellidos']."<br />";
    $mensaje .= "- Especialidad: ".$_POST['strEspecialidad']."<br />";
    $mensaje .= "- Provincia: ".$row_DatosCentros2['provincia'] ."<br />"; 
	$mensaje .= "- Localidad: ".$row_DatosCentros2['strLocalidad'] ."<br />";
    $mensaje .= "- Centro: ".$row_DatosCentros2['strNombre'] ."<br />";
    $mensaje .= "- Telefono: ".$_POST['intTelefono']."<br />";
    $mensaje .= "- Email: ".$_POST['strEmail']."<br />";
    $mensaje .= "- Mensaje: ".nl2br($_POST['strMensaje'])."<br /><br />";	
	EnviarCorreoHTML($destinatario,$asunto,utf8_decode($mensaje));
}
        } else {
                # set the error code so that we can display it
				 $error = $resp->error;
        }
}
?>
Y en el formulario...

Código:
                        <br><br>Mensaje:<br><textarea class="seleccionarea" id="mensajeregistro" name="strMensaje" placeholder="Mensaje:" rows="5" onClick="javascript:  borrarmensaje();"></textarea>
<div id="errorregistromensaje" class="ocultar texto-error">* Debe escribir un Mensaje</div>
<br><br>
                    
                    <?php
                    echo recaptcha_get_html($publickey, $error); ?> 
                        <div class="clear"></div>
                        <div class="btns">
  #5 (permalink)  
Antiguo 22/08/2014, 19:48
 
Fecha de Ingreso: mayo-2014
Ubicación: Valencia
Mensajes: 63
Antigüedad: 9 años, 11 meses
Puntos: 0
Respuesta: Validacion recaptcha

Ahora mi problema es que vuelve a la página y no muestra ningún mensaje de error, como puedo hacer que muestre un error en la propia página indicando que el captcha introducido es incorrecto?

Gracas
  #6 (permalink)  
Antiguo 30/08/2014, 02:31
 
Fecha de Ingreso: mayo-2014
Ubicación: Valencia
Mensajes: 63
Antigüedad: 9 años, 11 meses
Puntos: 0
Respuesta: Validación recaptcha

¿Ninguna sugerencia?

Etiquetas: formulario, html, mysql, recaptcha, registro, select, sql, usuarios, validacion, variable
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 21:56.