primero la imagen (1-A)...
Los jquery que tienen que bajar son esto dos (jquery.validate.js, jquery.min.js) van en la carpeta js...
mas abajo pongo el codigo como valide el formulario..
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta http-equiv="cache-control" content="no-cache">
<title>Formulario de contacto con HTML</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script type="text/javascript" src="js/jquery.contacto.js"> </script>
</head>
<body>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="post" name="frm_contact" id="frm_contact">
<div id="respond">
<h1>Envíanos tu consulta y te responderemos a la brevedad.</h1>
</br>
<div>
<label class="campo">Nombre:</label>
<input name="txtnombre" type="text" autofocus class="inputtext" id="txtnombre" autocomplete="off" />
</div>
<div>
<label class="campo">E-mail:</label>
<input name="txtemail" type="text" class="inputtext" id="txtemail" autocomplete="off" />
</div>
<div>
<label class="campo">Url:</label>
<input name="txturl" type="text" class="inputtext" id="txturl"/>
</div>
<div>
<label class="campo">Comentarios: </label>
<textarea name="txtcomment" id="txtcomment" maxlength="300" />
</textarea>
</div>
<div >
<label class="campo">Por favor, introduzca el código de seguridad</label>
<input name="tmptxt" type="text" class="inputcaptcha" id="tmptxt" maxlength="4" autocomplete="off" />
<img src="includes/captcha.php" id="captcha"> <a href="#" onClick="document.getElementById('captcha').src='includes/captcha.php?'+Math.random(); return false"> <img src="images/reload.gif" /></a>
<input name="action" type="hidden" value="checkdata" />
</div>
<div>
<input name="btnenviar" type="submit" id="btnenviar" value="Enviar información" />
</div>
<br/>
<?php
include("includes/contact_in_email.php");
if($error)
{
echo '<ul>';
foreach($error as $alerta)
{
echo "<li class='avertencia'>$alerta</li>\n";
}
echo '</ul>';}
?>
</div>
</form>
</body>
</html>
2)-Ahora hacemos la clase contact_in_email.php que va en la carpeta includes
<?php
session_start();
$error = array();
if(array_key_exists('btnenviar', $_POST)){
if ($_POST['action'] == "checkdata"){
$nombre = "";
$email = "";
$url= "";
$comment = "";
$captcha = "";
///---------------
$nombre= htmlentities($_POST['txtnombre']);
if($nombre == ""){
$error['txtnombre']= "Ingrese un nombre.";}
$email= htmlentities($_POST['txtemail']);
if($email==""){
$error['txtemail']="Ingrese un e-mail.";
}else if(!empty($email)){
// expresión regular para identificar caracteres ilegales en dirección email
$comprobarEmail = '/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix';
//rechazar la dirección email si no cumple la expresión regular
if (!preg_match($comprobarEmail, $email)) {
$error['txtemail'] = 'Por favor escribe una dirección email válida';}//fin de preg_match
}//fin del else y el if donde comprueba si es distinto a vacio $email
$comment = trim($_POST['txtcomment']);
if($comment == ""){
$error['txtcomment']= "Agradecemos los comentarios que nos pueda enviar";}
$captcha = trim($_POST['tmptxt']);
if($captcha == ""){
$error['tmptxt']= "Ingrese los dígitos de la imagen.";
}else if ($_SESSION['tmptxt'] != $_POST['tmptxt']) {
$error['tmptxt'] = 'El dígito ingresado no coincide, con la imagen.';}//fin de la validacion del formulario.
if(!$error){
try{
//script para procesar mail
$para ='tudireccion@gmail.com'; //utiliza tu propia dirección email
$asunto = 'Cuestionario enviado por Usuario';
//Lista de archivos que se esperan
$esperado = array('txtnombre', 'txtemail', 'txturl', 'txtcomment');
//Configurar archivos obligatorios
$obligatorio = array('txtnombre', 'txtemail', 'txtcomment','tmptxt');
//asume que no hay nada sospechoso
$sospechoso = false;
//crear un patrón para localizar frases sospechosas
$patron = '/Content-Type:|BCC:|CC:/i';
// function para comprobar frases sospechosas
function esSospechoso($val, $patron, $sospechoso){
// si la variable es un array, loop a través de cada elemento
// y pasarlo recursivamente de vuelta a la misma función
if (is_array($val)) {
foreach ($val as $item) {
esSospechoso($item, $patron, $sospechoso);}}else {
// si es encontrada una de las frases sospechosas, configurar Boolean a true
if (preg_match($patron, $val)) {
$sospechoso = true;}}}
//comprobar el array $_POST y todos los subarrays buscando contenido sospechoso
esSospechoso($_POST, $patron, $sospechoso);
if ($sospechoso){
$enviarMail = false;
unset($error);}else {
//Procesar las variables $_POST
foreach ($_POST as $key => $value) {
//asignar a variable temporalmente y vacía espacio blanco si no un array
$temp = is_array($value) ? $value : trim($value);
//si vacío y obligatorio, añadir a array $error
if (empty($temp) && in_array($key, $obligatorio)) {
array_push($error, $key);}
//En otro caso, asignar a una variable del mismo nombre que $key
elseif (in_array($key, $esperado)) {
${$key} = $temp; }}}
//Seguir sólo si todos los campos requeridos están OK
if (!$sospechoso && empty($error)){
//Construir el mensaje
$mensaje = "Nombre: $nombre\n\n";
$mensaje .= "Email: $email\n\n";
$mensaje .= "URL: $txturl\n\n";
$mensaje .= "$comment\r\n";
$mensaje .= "\n\n";
putenv('TZ=America/Montevideo');
$mensaje .= "Enviado el: " .date('d/m/Y | H:i:s',time())." | " .$_SERVER['REMOTE_ADDR'];
$mensaje .= "\n\n";
//Limitar tamaño de línea a 250 caracteres
$mensaje = wordwrap($mensaje, 300);
//crear cabeceras adicionales
$cabeceras ='From: tu nombre<'tudireccion@gmail.com>';
if (!empty($email)) {
$cabeceras .= "\r\nReply-To: $email";}
//Enviarlo
$enviarMail = mail ($para, utf8_decode($asunto), utf8_decode($mensaje), $cabeceras);
if ($enviarMail) {
echo "<strong class='avertencia'>Tu consulta se envió correctamente, te responderemos a la brevedad.</strong>";
//redireccionar a una pagina URL completa
//header('Location: http://www.'tudireccion.com');
exit;}}
//var_dump($_POST);
}catch(Exeception $ex)
{
echo "Problema en la base de datos al ingresar funcioanrio " .$ex->getMessage();
}
}//fin de si es distinto de error error...
}
}
$_POST= array();
?>
<?php
session_start();
$ancho=80;
$alto=30;
//imagen
$imagen = imagecreatefromgif("../images/bgcaptcha.gif");
//color de text
$colText = imagecolorallocate($imagen, 0, 0, 0);
//regilla
$lineColor = imagecolorallocate($imagen, 175, 175, 175);
imageline($imagen, 30, 5, 60, $alto,$lineColor);
imageline($imagen, 30, 5, 60, 55, $lineColor);
imageline($imagen, 40, 85, 70, 0, $lineColor);
imageline($imagen, 50, 55, 80, 55, $lineColor);
imageline($imagen, 20, 5, 60, 55, $lineColor);
imageline($imagen, 80, 35, 0, 0, $lineColor);
imageline($imagen, 20, 85, 80, 55, $lineColor);
imageline($imagen,25,0,25,$alto,$lineColor);
imageline($imagen,50,0,50,$alto,$lineColor);
imageline($imagen,75,0,75,$alto,$lineColor);
imageline($imagen,0,13,$ancho,13,$lineColor);
imageline($imagen,0,26,$ancho,26,$lineColor);
imageline($imagen,0,39,$ancho,39,$lineColor);
//Ruido
for ($i=0;$i<=700;$i++){
$randx=rand(0,100);
$randy=rand(0,55);
imagesetpixel($imagen,$randx,$randy,$lineColor);}
//TextoRandom
$str = substr(str_replace("0","",str_replace("O","",rand(9999,99999))),0,4);
//TextFont
$font = "../fonts/gunplay.ttf";
//session
$_SESSION['tmptxt'] = $str;
imagefttext($imagen, 16,rand(-5,0), 12, 20, $colText, $font,$str );
//imagestring($imagen, 5, 16, 7, $_SESSION['tmptxt'], $colText);
//Salida
header("Content-type: image/gif");
imagegif($imagen);
imagedestroy($imagen);
?>
4)-validando formulario con js...
en poca palabra lo que hice fue crear una clase js porque no me gusta tener todos los codigos aglomerado se ve muy feo... y alli hice una referencia a esa clase llamada
jquery.contacto.js ----esta clase tiene que ir en la carpeta js
<script type="text/javascript" src="js/jquery.contacto.js"> </script>
// JavaScript Document
$(document).ready(function() {
$.validator.addMethod("regex",function(value,element,regexp){
var re= new RegExp(regexp)
return this.optional(element) || re.test(value);
},"Solo caracteres Ej: Juan Pérez");
$("#frm_contact").validate({
rules:{
txtnombre:{
required:true,
regex:"[a-zA-Z]+$"
},
txtemail:{
required:true,
email:true
},
txtcomment:{
required:true,
}
//inicicio de mensaje
},
messages:{
txtnombre:{
required:"Ingrese su nombre y apellido"
//remote:"El usuario ya existe"
},
txtemail:{
required:"Ingrese una dirección de E-mail",
email:"Por favor escribe una dirección email válida"
},
txtcomment:{
required:"Agradecemos los comentarios que nos pueda enviar"
}
//fin del los mensaje
}
})
});
5)-y la hoja de estilo fue esta...
@charset "utf-8";
/* Reset */
html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary, time, mark, audio, video {
font-family: "Segoe UI", "Lucida Grande", "Lucida Sans Unicode", tahoma, Arial, Verdana, sans-serif;
font-size: 100%;
letter-spacing: 0em;
vertical-align: middle;
margin: 0px;
padding: 0px;
border: 0px;
outline: 0px;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: "";
content: none;
}
h1 {
font-size: 15px;
color: #666;
font-style: oblique;
}
form {
width: 50%;
margin: auto;
padding: 12px;
}
body, td, th {
color: #222;
}
td.label {
font-size: 13px;
padding-right: 3px;
width: 105px;
}
.label {
color: #1D2A5B;
text-align: right;
}
div label.campo {
width: auto;
margin: .4em 0;
display: block;
font-size: 13px;
}
div#respond {
border: 1px solid #CED5D7;
border-radius: 10px;
margin-top: auto;
padding: 25px;
border: 1px solid #CED5D7;
box-shadow: 0 0 0 3px #E5E5E5;
}
.inputtext, .inputpassword {
font-size: 14px;
padding: 6px;
border-radius: 4px;
border: 1px solid #CED5D7;
width: 250px;
}
.inputcaptcha {
font-size: 14px;
padding: 6px;
border-radius: 4px;
border: 1px solid #CED5D7;
width: 40px;
text-align: center;
}
textarea {
font-family: tahoma, verdana, arial, sans-serif;
font-size: 12px;
border-radius: 4px;
padding: 6px;
border: 1px solid #CED5D7;
resize: none; /* esta propiedad es para que el textarea no sea redimensionable */
width: 330px;
height: 120px;
}
input[type=submit] {
height: 30px;
overflow: hidden;
margin-top: 10px;
text-align: center;
}
.avertencia {
color: #FF0000;
font-family: "Segoe UI", Arial, Verdana, sans-serif;
font-size: 12px;
}
label.error {
background-color: #BC1010;
padding: 6px 12px;
border-radius: 4px;
color: white;
font-weight: bold;
margin-left: 16px;
position: absolute;
font-family: "Segoe UI", Arial, Verdana, sans-serif;
font-size: 10px;
}
.error:before { /* Este es un truco para crear una flechita */
content: '';
width: 0;
height: 0;
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
border-right: 8px solid #BC1010;
border-left: 8px solid transparent;
left: -16px;
position: absolute;
top: 5px;
pointer-events: none;
}
6)-Bueno y si todos lo copian bien le tiene que quedar asi...
No hay comentarios:
Publicar un comentario
Bienvenido