En la pag
Recursos de Quinti.net (Disponible en Español, Galego e Inglés) tenéis info sobre el tema que tb trataré aquí:
- Scripts PHP
- Formulario web seguro antispam con CAPTCHA
He sido atacado mil veces por spammers desde mi formulario de contacto, éstos usan robots y aprovechan ciertas vulnerabilidades de los formularios de correo para enviar su spam, y de paso, te llenan el buzón hasta tal punto, que te hacen prácticamente inservible el mail.
Para
solucionarlo, hay dos formas: introducir un CAPTCHA, validado mediante JavaScript, como veremos al final.
E introducir ciertas funciones en PHP que impiden estos ataques, como veremos en los ejemplos.
De momento, introducíos al problema.
-Links relacionados - Información:
CAPTCHA (Español) -
http://es.wikipedia.org/wiki/CaptchaDescripción del Problema (Inglés) -
http://www.modwest.com/help/kb9-314.htmlMás descripciones del problema (Inglés) -
http://www.anders.com/cms/75/Crack.Attempt/Spam.RelaySolución:He adaptado un magnífico script de CAPTCHA por validación en JavaScript de:
http://www.archreality.com/jcap/#j1 Veamos primero el código del formulario en PHP, consta de 2 archivos, contacto.php y gracias.php:
contacto.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=iso-8859-1" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="shortcut icon" href="image.gif" type="image/x-icon" />
<title>Quinti.net - Contact form example web secure anti spam with captcha</title>
<?
echo "<script type=\"text/javascript\">\n";
echo "<!--\n";
echo "function validar(form1) {\n";
echo "if (form1.name.value.length < 2) {\n";
echo "alert('";
echo "Inserte el nombre";;
echo "')\n";
echo "form1.name.focus();\n";
echo "return (false);}\n";
echo "var checkOK = \"ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ\" + \"abcdefghijklmnñopqrstuvwxyzáéíóú \";\n";
echo "var checkStr = form1.name.value;\n";
echo "var allValid = true;\n";
echo "var uword = hex_md5(document.getElementById('uword').value)\n";
echo "for (i = 0; i < checkStr.length; i++) {";
echo "ch = checkStr.charAt(i);\n";
echo "for (j = 0; j < checkOK.length; j++)\n";
echo "if (ch == checkOK.charAt(j))\n";
echo "break;\n";
echo "if (j == checkOK.length) {\n";
echo "allValid = false;\n";
echo "break;";
echo "}}\n";
echo "if (!allValid) {\n";
echo "alert('";
echo "Inser a name";
echo "');\n";
echo "form1.name.focus();\n";
echo "return (false);}\n";
echo "if ((form1.email.value.indexOf ('@', 0) == -1)||(form1.email.value.length < 9) || form1.email.value.indexOf ('.', 0)== -1 ){\n";
echo "alert('";
echo "Insert a valid email ";
echo "');\n";
echo "form1.email.focus();";
echo "return (false);}\n";
echo "if (form1.message.value.length < 7) {\n";
echo "alert('";
echo "Insert a message";
echo "');\n";
echo "form1.message.focus();";
echo "return (false);}\n";
echo "if (uword==cword[anum-1]) {\n";
echo "return true;}\n";
echo "else {\n";
echo "alert('";
echo "Insert image code (is to prevent spam) ";
echo "');\n";
echo "document.getElementById('uword').focus();\n";
echo "return false;}\n";
echo "return (true);}\n";
echo "-->\n";
echo "</script>\n";
?>
<script type="text/javascript" src="md5.js"></script>
<script type="text/javascript" src="jcap.js"></script>
<style type="text/css">
<!--
img{border:0;}
-->
</style>
</head>
<body>
<form method="post" onsubmit="return validar(this)" id="form1" action="gracias.php">
<p>
<input type="hidden" name="token" value="<?=$token?>" />
</p>
<p>
Nombre:*<input name="name" type="text" value="" />
</p>
<p>
E-mail:* <input name="email" type="text" value="" />
</p>
<p>
Asunto: <input name="phone" type="text" value="" />
</p>
<p>
Mensaje:* <br />
<textarea name="message" cols="30" rows="5"></textarea>
</p>
<p>
Insert the image code* (to prevent spam)</p>
<p><input type="text" name="uword" id="uword" value="" /> </p>
<p><script type="text/javascript">cimg()</script> </p>
<p>
<input type="submit" value="enviar" />
</p>
</form>
<p>fields with * are obligatory.
<a href="http://www.quinti.net" title="www.quinti.net - diseño web y multimedia"><img src="http://www.quinti.net/pics/q.png" width="21" height="14" alt="diseño web y multimedia" /></a></p>
<p>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http://www.w3.org/Icons/valid-xhtml11"
alt="Valid XHTML 1.1" height="31" width="88" /></a>
</p>
</body>
</html>
bien, vemos que en el
<head> escribimos en php el validador de campos en JavaScript.
Y también incluimos 2 archivos .js externos, propiedad de
http://www.archreality.com/jcap/#j1los cuales les he modificado una función.
Veamos ahora el procesaror del formulario, llamado gracias.php:
<?
@import_request_variables("gpc");//import variables
$youremail = "tudireccion@dominio.net "; //your mail
$subject = "el título del tema "; // for example, title of your contact page page - contact
$redirect = "contacto.php";//url to be redirected when contact form is sent
$secs = "5";// time in seconds will be redirected
if(eregi("MIME-Version:",$postVars)) {
mail("tudireccion@dominio.net", "Form Hijack Attempt", "A spam relay was attempted from the Web site and was blocked.", "From:SpamMonitor");
die();
} //block spam
$secret = 'ssshhitsasecret';
$token = md5(rand(1, 1000).$secret);
$_SESSION['token'] = $token;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" >
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=iso-8859-1" />
<title> Thank you, processor example anti spam with captcha by quinti.net, correct process</title>
<meta http-equiv="refresh" content="<?=$secs;?>;URL=<?=$redirect;?>" />
</head>
<body>
<?
// variables to stop spammers
$name = stripslashes($name);
$message = stripslashes($message);
$headers .= "From: " . $email . "\r\n\r\n";
//This is where the email is sent using your values from above. Be sure to update this if you change any fields in contact.php
mail("$youremail", "$subject","
Name: $name
Email: $email
Phone: $phone
Message: $message
",$headers);
// Strip \r and \n from the email address
$_POST['email'] = preg_replace("\r", "", $_POST['email']);
$_POST['email'] = preg_replace("\n", "", $_POST['email']);
$_SESSION['token'] = $token;
$token = md5(rand(1, 1000).$secret);
$secret = 'ssshhitsasecret';
$field = preg_replace( "/[\n\r]+/", " ", $field );
// Remove injected headers
$find = array("/bcc\:/i","/Content\-Type\:/i","/cc\:/i","/to\:/i");
$_POST['email'] = preg_replace($find, "", $_POST['email']);
$message = preg_replace($find, "", message);
$email=str_replace("\r","\n",$email);
$name=str_replace("\r","\n",$name);
$message=str_replace("\r","\n",$message);
$phone=str_replace("\r","\n",$phone);
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
ob_clean();
mail("$youremail", "Message Killed", "$message", "From: $name <$email>");
exit("Message killed.");
}
if (eregi('^(bcc$|content-type|mime-version|--)',$key))
print_error("Field names indicate exploit."); //bloqueo de spam
?>
<p>Thank you, the contact form was sent correctly. In 5 seconds you will be redirecte to index page.</p>
</body>
</html>
- ver
ejemplo sin estilos - ver
ejemplo con estilos - Descripción:
* Formulario de Contacto seguro antispam, invulnerable
* Validador de campos en JavaScript escrito en PHP (para insertar variables multilenguaje, si se desea, u otras variables)
* Frena a los spammers para usar tu formulario para enviar su basura: Garantizado
* CAPTCHA para evitar Spam con validación JavaScript
* Fácil de instalar y configurar
* Validado XHTML 1.1- NOTA IMPORTANTE:
Para quitar el link del creador, y/o para su uso comercial, el formulario cuesta 30€ , COMPRAR AHORA VÍA PAYPAL + info en formulario de contacto- descargar el archivo completo
quinti.net_form+jcap.rar (942 kb.) Dudas sobre la instalación aquí en este foro y/o en
formulario de contacto