Ver Mensaje Individual
  #1 (permalink)  
Antiguo 27/04/2008, 14:17
Avatar de leskolpykos
leskolpykos
 
Fecha de Ingreso: junio-2007
Ubicación: Caracas
Mensajes: 96
Antigüedad: 17 años, 9 meses
Puntos: 0
Pregunta error crítico en código captcha para evitar spam

hola amigos, tengo un libro de visitas, el cual los spammer estan destrozando son sus mensajes con código malicioso. Conseguí en la red un código captcha muy sencillo y efectivo pero algo no funciona bien, ya que genera la imagen y asi ponga los caracteres que aparecen en la imagen o ponga otros, igual guarda el mensaje del usuario. es decir no me está validando q los caracteres sean correctos.

acá les desgloso ésto:

este es el código php que publica el mensaje del usuario, el cual funciona perfecto

Código PHP:
<?php require_once('conexion.php'); ?>
<?php
function GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $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;
}

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

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form2")) {
  
$insertSQL sprintf("INSERT INTO libro (id, usuario, email, mensaje) VALUES (%s, %s, %s, %s)",
                       
GetSQLValueString($_POST['id'], "int"),
                       
GetSQLValueString($_POST['usuario'], "text"),
                       
GetSQLValueString($_POST['email'], "text"),
                       
GetSQLValueString($_POST['mensaje'], "text"));

  
mysql_select_db($database_localhost);
  
$Result1 mysql_query($insertSQL) or die(mysql_error());

  
$insertGoTo "default.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}
?>
en ése código hay que agregar éste fragmento que es el que genera la imagen captcha pero no se donde colocarlo pues ya lo he probado de muchas formas y no funciona

Código PHP:
<?php 
session_start
();

if( isset(
$_POST['submit'])) {
   if( 
$_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
        
// Insert you code for processing the form here, e.g emailing the submission, entering it into a database. 
        
echo 'Thank you. Your message said "'.$_POST['message'].'"';
        unset(
$_SESSION['security_code']);
   } else {
        
// Insert your code for showing an error message here
        
echo 'Sorry, you have provided an invalid security code';
   }
} else {
?>
aca el formulario donde el usuario ingresa su mensaje

Código HTML:
 <form action="form.php" method="post">
		<label for="name">Name: </label><input type="text" name="name" id="name" /><br />
		<label for="email">Email: </label><input type="text" name="email" id="email" /><br />
		<label for="message">Message: </label><textarea rows="5" cols="30" name="message" id="message"></textarea><br />
		<img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" /><br />
		<label for="security_code">Security Code: </label><input id="security_code" name="security_code" type="text" /><br />
		<input type="submit" name="submit" value="Submit" />
	</form>

<?php
	}
?> 

éste a continuación es el archivo CaptchaSecurityImages.php que gestiona la imagen captcha el cual funciona perfecto..

Código PHP:
<?php
session_start
();

class 
CaptchaSecurityImages {

    var 
$font 'monofont.ttf';

    function 
generateCode($characters) {
        
/* list all possible characters, similar looking characters and vowels have been removed */
        
$possible '23456789bcdfghjkmnpqrstvwxyz';
        
$code '';
        
$i 0;
        while (
$i $characters) { 
            
$code .= substr($possiblemt_rand(0strlen($possible)-1), 1);
            
$i++;
        }
        return 
$code;
    }

    function 
CaptchaSecurityImages($width='120',$height='40',$characters='6') {
        
$code $this->generateCode($characters);
        
/* font size will be 75% of the image height */
        
$font_size $height 0.75;
        
$image = @imagecreate($width$height) or die('Cannot initialize new GD image stream');
        
/* set the colours */
        
$background_color imagecolorallocate($image255255255);
        
$text_color imagecolorallocate($image2040100);
        
$noise_color imagecolorallocate($image100120180);
        
/* generate random dots in background */
        
for( $i=0$i<($width*$height)/3$i++ ) {
            
imagefilledellipse($imagemt_rand(0,$width), mt_rand(0,$height), 11$noise_color);
        }
        
/* generate random lines in background */
        
for( $i=0$i<($width*$height)/150$i++ ) {
            
imageline($imagemt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
        }
        
/* create textbox and add text */
        
$textbox imagettfbbox($font_size0$this->font$code) or die('Error in imagettfbbox function');
        
$x = ($width $textbox[4])/2;
        
$y = ($height $textbox[5])/2;
        
imagettftext($image$font_size0$x$y$text_color$this->font $code) or die('Error in imagettftext function');
        
/* output captcha image to browser */
        
header('Content-Type: image/jpeg');
        
imagejpeg($image);
        
imagedestroy($image);
        
$_SESSION['security_code'] = $code;
    }

}

$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > $_GET['characters'] : '6';

$captcha = new CaptchaSecurityImages($width,$height,$characters);

?>

por consiguiente el unico problema es el trozo de código que va dentro del código php para que valide si los caracteres son correctos o no...

ojala alguno pueda asesorarme porque ya los spammer me estan volviendo loco
__________________
www.luisespectaculo.net el portal de artistas y farándula más grande de Venezuela!

Última edición por leskolpykos; 07/08/2008 a las 17:59