1-) Así esta en el wampserver(1-A)
2-)Formato de la pagina login.php

3-) Código html del formato login.php
Los jquery que tienen que bajar son esto dos (jquery.validate.js, jquery.min.js) van en la carpeta js...
(-mas abajo pongo el script como validar el formulario con jquery)..
<!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 login</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.login.js"> </script>
</head>
<body>
<div >
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="post" name="frm_login" id="frm_login">
<div id="respond">
<h1>Iniciar sesión.</h1>
</br>
<div>
<label class="campo">Nombre de usuario:</label>
<input name="txtusername" type="text" autofocus class="inputtext" id="txtusername" autocomplete="off" />
</div>
<div>
<label class="campo">Contraseña:</label>
<input name="txtpassword" type="password" class="inputtext" id="txtpassword" autocomplete="off" />
</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="Iniciar sesión" />
</div>
<br/>
<?php
include("includes/form_in_login.php");
if($error)
{
echo '<ul>';
foreach($error as $alerta)
{
echo "<li class='avertencia'>$alerta</li>\n";
}
echo '</ul>';}
?>
</div>
</form>
</div>
</body>
</html>
4-)Validando el formulario con jquery con el script jquery.login.js
// JavaScript Document
$(document).ready(function() {
$.validator.addMethod("regex",function(value,element,regexp){
var re= new RegExp(regexp)
return this.optional(element) || re.test(value);
},"Ingrese el usuario tal cual se registro en nuestro sistema");
$("#frm_login").validate({
rules:{
txtusername:{
required:true,
regex:"^[a-zA-Z0-9_]+$"
},
txtpassword:{
required:true
}
//inicicio de mensaje
},
messages:{
txtusername:{
required:"Ingrese su nombre de usuario"
},
txtpassword:{
required:"Ingrese una contraseña"
}
//fin del los mensaje
}
}
)
});
5-)Ahora la clase form_in_login.php que va en la carpeta includes..
<?php
session_start();
$error = array();
if(array_key_exists('btnenviar',$_POST)){
if ($_POST['action'] == "checkdata") {
$username = "";
$password = "";
$tmptxt = "";
$sesion_login = true;
include("oConexion.php");
$conexion = conectar();
//Validar que los campos usuario y passwords no esten vacio.
$username = htmlentities(trim($_POST['txtusername']));
if($username == "")
{
$error['txtusername'] = "Ingrese un nombre de usuario";
}
$password = htmlentities(trim($_POST['txtpassword']));
if($password == "")
{
$error['txtpassword'] = "Ingrese un password";
}
//catchap
$tmptxt = trim($_POST['tmptxt']);
if($tmptxt== "")
{
$error['tmptxt']="Ingrese los dígitos de la imagen";
}else if ($_SESSION['tmptxt'] != $_POST['tmptxt']) {
$error['tmptxt'] = 'Ingrese los dígitos de la imagen';}
//si es distinto el error
if (!$error){
//compruebo el usuario y pass para asegurarme..
if ($_POST['txtusername']) {
$query = mysql_query("SELECT usuario FROM usuarios WHERE usuario = '$username'") or die(mysql_error());
$data = mysql_fetch_array($query);
if($data['usuario'] != $username) {
$error['txtusername'] = "El usuario y/o la clave no son correcto.";
} else if ($_POST['txtpassword']){
$query = mysql_query("SELECT contrasena FROM usuarios WHERE contrasena = '$password'") or die(mysql_error());
$data = mysql_fetch_array($query);
if($data['contrasena'] != $password) {
$error['txtpassword'] = "El usuario y/o la clave no son correcto";
}else{
//y si todos se cumple bien hago la consulta
$query = mysql_query("SELECT usuario,contrasena,email,admin_priv FROM usuarios WHERE usuario ='".$username."' AND contrasena = '".$password."'");
$row = mysql_fetch_array($query);
$_SESSION["u_usuario"] = $row['admin_priv'];//para saber que tipo de usuario se logeo
$_SESSION["s_username"] = $row['usuario'];//saber el nombre del usuario
$_SESSION["s_email"] = $row['email'];//saber el email del usuario
//aca compruebo si es usuario oh administrador
if ($_SESSION["u_usuario"] =='u'){
header("location: site/index.php");//aca me voy para la carpeta usuario
}elseif($_SESSION["u_usuario"] =='a'){
header("location: admin/index.php");}//aca para la carpeta administrador
}//terminar la consulta
}
}//aca termina la comprobacion de usuarios y pass
}//fin de if de !error
}
}
$_POST = array();
?>
6-) Código que va en el index.php que se encuentra en la carpeta site, alli pegan este codigo
<?php session_start();
if($_SESSION["s_username"]!=""){ ?>
<!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>Welcome usuario</title>
<link rel="stylesheet" type="text/css" href="../style.css">
</head>
<body>
<div id="welcome">
<?php //session_start();
if ($_SESSION["u_usuario"] =='u') {?>
<!--ACA VA TODOS EN CUERPO DE LA PAGINA-->
<h1 class="usuario">
<?php echo("<p>Bienvenido ( " .$_SESSION['s_username']. " ) </p>");?>
</h1>
<br />
<hr />
<?php } else{
header('Location: ../login.php');
exit();}?>
</div>
</body>
</html>
<?php }else{
header('Location: ../login.php');
exit();}?>
7-) Código que va en el index.php que se encuentra en la carpeta admin, alli pegan este codigo
<?php session_start();
if($_SESSION["s_username"]!=""){ ?>
<!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>Welcome Admin</title>
<link rel="stylesheet" type="text/css" href="../style.css">
</head>
<body>
<div id="welcome">
<?php //session_start();
if ($_SESSION["u_usuario"] =='a') {?>
<!--ACA VA TODOS EN CUERPO DE LA PAGINA-->
<h1 class="usuario">
<?php echo("<p>Bienvenido ( " .$_SESSION['s_username']. " ) </p>");?>
</h1>
<br />
<hr />
<?php } else{
header('Location: ../login.php');
exit();}?>
</div>
</body>
</html>
<?php }else{
header('Location: ../login.php');
exit();}?>
8-)Hoja de estilo, este codigo se ve un poco largo porque estoy usando esta hoja para otra cosa... pero igual pego el código completo...
@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;
}
#welcome {
width: 50%;
margin: auto;
padding: 12px;
border: 1px solid #CED5D7;
border-radius: 10px;
margin-top: auto;
padding: 25px;
border: 1px solid #CED5D7;
box-shadow: 0 0 0 3px #E5E5E5;
}
.usuario {
font-size: 22px;
color: #000;
font-weight: bold;
text-align: center;
}
Hagan la estructura como le mostré en la primera imagen (1-A)
ante de todos tienen que bajar el tipo de letra que yo use, si no le da error el captcha.. yo use tipo VeraBd.ttf este tipo de letra va en la carpeta fonts
9-)-Ahora el famoso captcha... crear una clase captcha.php esta clase va en la carpeta includes.
<?php
session_start();
$ancho=80;
$alto=30;
//imagen
$imagen = imagecreatefromgif("../images/bgcaptcha.gif");
//color de text
$colText = imagecolorallocate($imagen, 170, 160, 170);
//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/VeraBd.ttf";
//session
$_SESSION['tmptxt'] = $str;
imagefttext($imagen, 14,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);
?>
10-)conexion a la base de datos(asi se llama la clase oConexion.php).
<?php
function conectar()
{
$mysql_host = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "ejemplousuarios2012";
if(!$conexion= mysql_connect($mysql_host,$mysql_user,$mysql_password))
{
die("No se puedo ejecutar la conexion ". mysql_error());
}
if(!mysql_select_db($mysql_database, $conexion))
{
die("No se pudo seleccionar la base de datos ". mysql_error());
}
return $conexion;
}
?>
11-)La tabla usuarios... asi fue creada la tabla..
CREATE TABLE IF NOT EXISTS `usuarios` (
`co_digo` int(11) unsigned NOT NULL AUTO_INCREMENT,
`admin_priv` enum('u','a') NOT NULL,
`usuario` varchar(30) NOT NULL,
`contrasena` varchar(30) NOT NULL,
`email` varchar(50) NOT NULL,
`fecha_ingreso` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`co_digo`),
UNIQUE KEY `o_usuario` (`usuario`) USING BTREE,
UNIQUE KEY `o_email` (`email`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
No hay comentarios:
Publicar un comentario
Bienvenido