Foros aprenderaprogramar.com

Aprender a programar => De todo un poco... => Mensaje iniciado por: aagustin en 19 de Abril 2015, 02:35

Título: Securizar formulario con securimage captcha php form registro usuarios código
Publicado por: aagustin en 19 de Abril 2015, 02:35
Hola amigos,

No soy un experto en PHP y tengo un problema con el archivo que adjunto. Este es un formulario de registro, el proceso del formulario funciona muy bien pero el check del Captcha no, porque registra a quien lena el formulario sin tomar en cuenta la comprobación del código de captcha ingresado previamente. Los códigos de chequeo y verificación están a partir de la línea 52.

Les voy  agradecer mucho que me ayuden en este problema, y me comenten cuál es el error.

Pueden bajar el archivo PHP aquÍ:

http://www.thkseditores.pe.hu/otros/insert_users_captcha.rar

Muchas gracias,
AAgustín.
Título: Re:Problemas con securimage captcha php
Publicado por: Alex Rodríguez en 19 de Abril 2015, 21:18
Hola, adjunto el código que indicas pues es más cómodo revisarlo pudiendo acceder a él directamente:

Código: [Seleccionar]
<?phpsession_start(); ?>

<?php require_once('Connections/conexion_usuarios.php'); ?>


<?phpif (!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;}}// *** Redirect if username exists$MM_flag="MM_insert";if (isset($_POST[$MM_flag])) {  $MM_dupKeyRedirect="ya_existe_registro.php";  $loginUsername = $_POST['email'];  $LoginRS__query = sprintf("SELECT email FROM usuarios WHERE email=%s", GetSQLValueString($loginUsername, "text"));  mysql_select_db($database_conexion_usuarios, $conexion_usuarios);  $LoginRS=mysql_query($LoginRS__query, $conexion_usuarios) or die(mysql_error());  $loginFoundUser = mysql_num_rows($LoginRS);  //if there is a row in the database, the username was found - can not add the requested username  if($loginFoundUser){    $MM_qsChar = "?";		//check captcha    	include_once 'http://localhost/sitio4/securimage/securimage.php'; 	$securimage = new Securimage();	// Verifify captchaif ($secureimage->check($post['captcha_code']) == false){    echo "The security code entered was incorrect.<br />";	echo "<a href='javascript:history.go(-1)'>Try again</a>.";	exit;    	   	   }     //append the username to the redirect page    if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar = "&";    $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar ."requsername=".$loginUsername;    header ("Location: $MM_dupKeyRedirect");    exit;  }}   	  $editFormAction = $_SERVER['PHP_SELF'];  if (isset($_SERVER['QUERY_STRING'])) {  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);}if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {  $insertSQL = sprintf("INSERT INTO usuarios (nombre, apellido, email, clave, pais, ciudad) VALUES (%s, %s, %s, %s, %s, %s)",                       GetSQLValueString($_POST['nombre'], "text"),                       GetSQLValueString($_POST['apellido'], "text"),                       GetSQLValueString($_POST['email'], "text"),                       GetSQLValueString($_POST['clave'], "text"),                       GetSQLValueString($_POST['pais'], "text"),                       GetSQLValueString($_POST['ciudad'], "text"));   mysql_select_db($database_conexion_usuarios, $conexion_usuarios);  $Result1 = mysql_query($insertSQL, $conexion_usuarios) or die(mysql_error());  $insertGoTo = "registro_ok.php";  if (isset($_SERVER['QUERY_STRING'])) {    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";    $insertGoTo .= $_SERVER['QUERY_STRING'];  }  header(sprintf("Location: %s", $insertGoTo));}		?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type" />
<meta content="es-pe" http-equiv="Content-Language" />
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="estilos.css">
<style type="text/css">
#apDiv1 {
position: absolute;
width: 630px;
height: 90px;
z-index: 1;
left: 620px;
top: 95px;
background-color: #FAFAFA;
text-align: center;
font-size: 36px;
}
#apDiv2 {
position: absolute;
width: 630px;
height: 385px;
z-index: 2;
left: 620px;
top: 184px;
background-color: #FAFAFA;
text-align: center;
color: #D56939;
}
#apDiv1 p {
font-size: 36px;
}
#apDiv2 #form1 table tr td {
font-size: 24px;
}
#apDiv3 {
position: absolute;
width: 303px;
height: 243px;
z-index: 3;
left: 90px;
top: 272px;
text-align: center;
}
#apDiv4 {
position: absolute;
width: 254px;
height: 249px;
z-index: 3;
left: 124px;
top: 85px;
text-align: center;
}
#apDiv5 {
position: absolute;
width: 200px;
height: 115px;
z-index: 3;
left: 98px;
top: 255px;
}
#apDiv6 {
position: absolute;
width: 200px;
height: 115px;
z-index: 3;
}
#apDiv7 {
position: absolute;
width: 292px;
height: 248px;
z-index: 3;
left: 90px;
top: 218px;
text-align: center;
}
#apDiv2 p a {
color: #D56939;
}
</style>
<script type="text/javascript">
function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' Debe ingresar una dirección de correo electrónico.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' es requerido.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' es requerido.\n'; }
    } if (errors) alert('DATOS OBLIGATORIOS PARA PODER REGISTRARSE:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
</script>
</head>
<body background="images/fondoserv.jpg" onfocus="MM_validateForm('nombre','','R','apellido','','R','email','','RisEmail','clave','','R','pais','','R','ciudad','','R');return document.MM_returnValue">
     <header class="header2">
       <div class="wrapper">
       </div>
<nav>
<a href="index.html" class="auto-style2">INICIO</a>
<a href="#" class="auto-style2">INFO</a>
<a href="#" class="auto-style2">SERVICIOS</a>
<a href="#" class="auto-style2">BLOG</a>
<a href="#" class="auto-style2">CONTACTO</a>
</nav>
</div>
</header>


<!--- Empieza contenido del texto---><!-- TemplateBeginEditable name="doctitle" -->
<title>Registro de usuarios</title>
<!-- TemplateEndEditable -->
<style type="text/css">
 p.MsoNormal
{margin-top:0cm;
margin-right:0cm;
margin-bottom:8.0pt;
margin-left:0cm;
line-height:107%;
font-size:11.0pt;
font-family:"Calibri",sans-serif;
}
.auto-style2 {
font-family: "Humanst521 BT";
}
p.Aurelio
{margin-bottom:.0001pt;
text-align:justify;
font-size:12.0pt;
font-family:"Times New Roman",serif;
margin-left: 0cm;
margin-right: 0cm;
margin-top: 0cm;
}
p.MsoListParagraph
{margin-top:0cm;
margin-right:0cm;
margin-bottom:8.0pt;
margin-left:36.0pt;
line-height:107%;
font-size:11.0pt;
font-family:"Calibri",sans-serif;
}
</style>
<div id="apDiv7"><img src="images/rombo-id-web.png" width="405" height="320" /></div>
</head>

<body style="background-attachment: fixed; background-color: #FFFFFF; background-image: url('../Fotografías/Fondos%20Pantalla/fondo-tres.jpg'); background-repeat: no-repeat; background: url('images/fondoserv.jpg') no-repeat fixed center;">

<div id="apDiv1">
  <p>&nbsp;</p>
  <p>Registro de usuario</p>
</div>
<div id="apDiv2">
  <p>&nbsp;</p>
  <form action="
<?php echo $editFormAction; ?>
" method="post" name="form1" id="form1">
    <table align="center" class="wrapper">
      <tr valign="baseline">
        <td nowrap="nowrap" align="right">Nombre:</td>
        <td><input name="nombre" type="text" id="nombre" onfocus="MM_popupMsg('Debe ingresar la totalidad de los datos...')" value="" size="32" /></td>
      </tr>
      <tr valign="baseline">
        <td nowrap="nowrap" align="right">Apellido:</td>
        <td><input name="apellido" type="text" id="apellido" value="" size="32" /></td>
      </tr>
      <tr valign="baseline">
        <td nowrap="nowrap" align="right"> Correo electr&oacute;nico: </td>
        <td><input name="email" type="text" id="email" onblur="MM_validateForm('nombre','','R','apellido','','R','email','','RisEmail','clave','','R','pais','','R','ciudad','','R','codpost','','R');return document.MM_returnValue" value="" size="32" /></td>
      </tr>
      <tr valign="baseline">
        <td nowrap="nowrap" align="right">Contrase&ntilde;a:</td>
        <td><input name="clave" type="password" id="clave" onfocus="MM_validateForm('nombre','','R','apellido','','R','email','','RisEmail','clave','','R','pais','','R');return document.MM_returnValue" value="" size="32" /></td>
      </tr>
      <tr valign="baseline">
        <td nowrap="nowrap" align="right">Pa&iacute;s:</td>
        <td><input name="pais" type="text" id="pais" value="" size="32" /></td>
      </tr>
      <tr valign="baseline">
        <td nowrap="nowrap" align="right">Ciudad:</td>
        <td><input name="ciudad" type="text" id="ciudad" value="" size="32" /></td>
      </tr>
      <tr valign="baseline">
        <td nowrap="nowrap" align="right"><img id="captcha" src="http://localhost/sitio4/securimage/securimage_show.php" alt="CAPTCHA Image" /></td>
        <td><p>
          <input type="text" name="captcha_code" size="8" maxlength="6" />
        <a href="#" onclick="document.getElementById('captcha').src = 'http.//localhost/sitio4/securimage/securimage_show.php?' + Math.random(); return false"> &iexcl;Prueba con otra imagen</a><a href="#">!</a></p>
        <p>&nbsp;</p></td>
      </tr>
      <tr valign="baseline">
        <td nowrap="nowrap" align="right">&nbsp;</td>

        <td><input type="submit" class="wrapper" value="Guarda tus datos" /></td>
      </tr>
     
     
    </table>
    <input type="hidden" name="MM_insert" value="form1" />
  </form>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
</div>
</body>

</html>

Saludos
Título: Re:Problemas con securimage captcha php
Publicado por: Alex Rodríguez en 19 de Abril 2015, 21:21
Sobre el problema que comentas, en el código tenemos llamadas a estos archivos:

require_once('Connections/conexion_usuarios.php'); que supongo es la conexión con la base de datos

Y por otro lado:

include_once 'http://localhost/sitio4/securimage/securimage.php';  que sí puede estar relacionado con el problema

¿Tienes el código de este archivo?

Saludos
Título: Re:Securizar formulario con securimage captcha php
Publicado por: aagustin en 20 de Abril 2015, 15:53
Hola,

El código securimage es del servicio que brinda el captcha, lamentablemente me dice que es muy largo y no puedo pegarlo, la dirección para bajarlo directamente es:

http://www.thkseditores.com/otros/securimage.rar

Gracias.
Título: Re:Securizar formulario con securimage captcha php
Publicado por: Alex Rodríguez en 20 de Abril 2015, 16:57
El enlace que has puesto parece que no funciona  ???
Título: Re:Securizar formulario con securimage captcha php
Publicado por: aagustin en 20 de Abril 2015, 18:09
El programa toma bien el enlace, no hace ninguna observación.
Título: Re:Securizar formulario con securimage captcha php
Publicado por: Alex Rodríguez en 20 de Abril 2015, 22:14
Hola no sé si a ti te permite descargar algo pero a mí cuando pulso en http://www.thkseditores.com/otros/securimage.rar me dice "no encontrado"

Saludos
Título: Re:Securizar formulario con securimage captcha php
Publicado por: aagustin en 20 de Abril 2015, 23:55
Perdón, es http://www.thkseditores.pe.hu/otros/securimage.rar

Gracias, saludos.
Título: Re:Securizar formulario con securimage captcha php
Publicado por: Alex Rodríguez en 21 de Abril 2015, 08:09
Hola, a mí me sigue diciendo "no encontrado"  ::)
Título: Re:Securizar formulario con securimage captcha php
Publicado por: aagustin en 21 de Abril 2015, 15:57
SECURIMAGE.PHP    ;D

Título: Re:Securizar formulario con securimage captcha php
Publicado por: Alex Rodríguez en 21 de Abril 2015, 23:23
Ahora sí... Hola en este código he visto algo que me resulta extraño.

Código: [Seleccionar]
$MM_flag="MM_insert";
if (isset($_POST[$MM_flag])) {
  $MM_dupKeyRedirect="ya_existe_registro.php";
  $loginUsername = $_POST['email'];
  $LoginRS__query = sprintf("SELECT email FROM usuarios WHERE email=%s", GetSQLValueString($loginUsername, "text"));
  mysql_select_db($database_conexion_usuarios, $conexion_usuarios);
  $LoginRS=mysql_query($LoginRS__query, $conexion_usuarios) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);

  //if there is a row in the database, the username was found - can not add the requested username
  if($loginFoundUser){
    $MM_qsChar = "?";

//check captcha   
include_once 'http://localhost/sitio4/securimage/securimage.php';
$securimage = new Securimage();
// Verifify captcha
if ($secureimage->check($post['captcha_code']) == false){
    echo "The security code entered was incorrect.<br />";
echo "<a href='javascript:history.go(-1)'>Try again</a>.";
exit;           
}

    //append the username to the redirect page
    if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar = "&";
    $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar ."requsername=".$loginUsername;
    header ("Location: $MM_dupKeyRedirect");
    exit;
  }
 
}

El formulario es un formulario de registro. El usuario introduce los datos y el captcha. Si el captcha es erróneo no se debe avanzar. Sin embargo aquí

Código: [Seleccionar]
$loginUsername = $_POST['email'];
  $LoginRS__query = sprintf("SELECT email FROM usuarios WHERE email=%s", GetSQLValueString($loginUsername, "text"));
  mysql_select_db($database_conexion_usuarios, $conexion_usuarios);
  $LoginRS=mysql_query($LoginRS__query, $conexion_usuarios) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);

Lo que parece hacer es tomar el valor email  que le llega del formulario (en $loginUsername = $_POST['email']; ) para comprobar si el usuario existe en la base de datos, y sólo si existe, hace la comprobación del captcha.

¿No tendría que estar la comprobación del captcha antes de cualquier cosa? Tal y como está escrito parece que sólo verifica el captcha si el usuario existe en la base de datos, pero esto no tendría sentido, la verificación del captcha tendría que ser anterior a cualquier otro paso  ::)

Saludos
Título: Re:Securizar formulario con securimage captcha php
Publicado por: aagustin en 21 de Abril 2015, 23:30
Hola Alex,

Te agradezco los comentarios. Para tal caso, ¿en qué lugar del script crees que debería estar situada la sentencia?

Muchas gracias,
Título: Re:Securizar formulario con securimage captcha php
Publicado por: Alex Rodríguez en 21 de Abril 2015, 23:48
Habría que probarlo, no estoy muy seguro de qué responderá si no le llegan valores por post (if ($secureimage->check($post['captcha_code']) == false){)  pero sería justo al principio

Código: [Seleccionar]
<?phpsession_start(); ?>

<?php require_once('Connections/conexion_usuarios.php'); ?>


<?php	//check captcha    	include_once 'http://localhost/sitio4/securimage/securimage.php'; 	$securimage = new Securimage();	// Verifify captchaif ($secureimage->check($post['captcha_code']) == false){    echo "The security code entered was incorrect.<br />";	echo "<a href='javascript:history.go(-1)'>Try again</a>.";	exit;    	   	   }if (!function_exists("GetSQLValueString")) {......

Saludos