Foros del Web » Programando para Internet » PHP »

error crítico en código captcha para evitar spam

Estas en el tema de error crítico en código captcha para evitar spam en el foro de PHP en Foros del Web. 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 ...
  #1 (permalink)  
Antiguo 27/04/2008, 14:17
Avatar de leskolpykos  
Fecha de Ingreso: junio-2007
Ubicación: Caracas
Mensajes: 96
Antigüedad: 16 años, 10 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
  #2 (permalink)  
Antiguo 28/04/2008, 10:21
Avatar de eft0  
Fecha de Ingreso: junio-2003
Ubicación: Santiago - Chile
Mensajes: 635
Antigüedad: 20 años, 10 meses
Puntos: 9
Re: error crítico en código captcha para evitar spam

El codigo que no sabes donde colocar va dentro del form.php con la salvadedad del session_start() que lo debes dejar en la primera Linea , y luego, el codigo.
  #3 (permalink)  
Antiguo 29/04/2008, 07:34
Avatar de leskolpykos  
Fecha de Ingreso: junio-2007
Ubicación: Caracas
Mensajes: 96
Antigüedad: 16 años, 10 meses
Puntos: 0
Re: error crítico en código captcha para evitar spam

esto es lo que coloqué y no hace absolutamente nada ni detecta si es correcto el codigo o no, ni guarda el mensaje del usuario ni nada deoxxxx porqueee?

Código:
<?php require_once('../home/conexion.php'); ?>
<?php

extract($_POST); 

session_start(); 
if(isset($_POST[content])) { 
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.  
unset($_SESSION['security_code']); 

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"] == "form1")) {
  $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));
} else { 
// Insert your code for showing an error message here 
echo "<script>alert('Disculpa! el código de seguridad está incorrecto'); window.location='javascript:history.back()';</script>"; 
} 
} 

?>
__________________
www.luisespectaculo.net el portal de artistas y farándula más grande de Venezuela!
  #4 (permalink)  
Antiguo 29/04/2008, 08:42
 
Fecha de Ingreso: septiembre-2005
Mensajes: 840
Antigüedad: 18 años, 7 meses
Puntos: 84
Re: error crítico en código captcha para evitar spam

Mirate este post :

http://www.forosdelweb.com/f18/aport...aptcha-570642/
  #5 (permalink)  
Antiguo 07/08/2008, 18:02
Avatar de leskolpykos  
Fecha de Ingreso: junio-2007
Ubicación: Caracas
Mensajes: 96
Antigüedad: 16 años, 10 meses
Puntos: 0
Respuesta: error crítico en código captcha para evitar spam

si ese lo encontré en las faqs pero el link no sirve o ya no existe el archivo
__________________
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 18:31
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 02:37.