Help - Search - Members - Calendar
Full Version: Como Hacer Un Login De Usuarios En My Base De Datos?
Zymic Webmaster Forums > Zymic Free Web Hosting > Databases & MySQL
SilvioGuerrero
Hola que tal comunidad zymic, tengo todos los scripts para crear un loguin en mi pagina pero no se por donde empezar, no se como montarla en nuestra base de datos, aqui les dejo los pasos que he realizado para que me ayuden, si alguien me puede orientar por favor...

-----COMENCEMOS-----
1.- Para comenzar es basico acceder a nuestra base de datos y crear las tablas nesesarias para que el Script se ejecute correctamente.

create table usuarios (
id smallint(5) unsigned not null auto_increment,
fecha int(10) unsigned not null,
nick varchar(20) not null,
contrasena varchar(32) not null,
email varchar(40) not null,
pais varchar(20) not null,
edad tinyint(2) unsigned not null,
sexo enum('0','1') not null,
descripcion tinytext not null,
web varchar(100) not null,
ip varchar(15) not null,
primary key (id),
key (nick,contrasena)
)

2.- Una vez creadas las tablas , procedemos a crear el archivo que llamaremos "config.php" , el cual constara de la llamada a nuestra base de datos, password, usuario y demas ...

<?
unset($config) ;
$config[1] = 'localhost' ; # Puede ser "localhost" aunque también una URL o una IP
$config[2] = 'usuario' ; # Usuario de la base de datos
$config[3] = 'contrasena' ; # Contraseña de la base de datos
$config[4] = 'basededatos' ; # Nombre de la base de datos

$conectar = @mysql_connect($config[1],$config[2],$config[3]) or exit('Datos de conexión incorrectos.') ;
mysql_select_db($config[4],$conectar) or exit('No existe la base de datos.') ;
?>



3.- Ya teniendo nuestras tablas creadas y nuestro archivo "config.php" , procedemos a crear el formulario para registrar a los usuarios, para ello creamos el siguiente archivo llamado "registrar.php"

<?
if($_POST[enviar]) {
require 'config.php' ;
function quitar($texto) {
$texto = trim($texto) ;
$texto = htmlspecialchars($texto) ;
$texto = str_replace(chr(160),'',$texto) ; # Elimina espacios que no pueden ser borrados por trim()
return $texto ;
}
$nick = quitar($_POST[nick]) ;
$email = quitar($_POST[email]) ;
$con = mysql_query("select count(id) from usuarios where nick='$nick' or email='$email'") ;
if(mysql_result($con,0,0)) {
echo 'El nick ya existe en la base de datos o ya está registrado el email. Haz click <a href="java script:history.back()">aquí</a> para regresar.' ;
}
else {
$fecha = time() ;
$contrasena = md5(md5(quitar($_POST[contrasena]))) ;
$sexo = quitar($_POST[sexo]) ;
mysql_query("insert into usuarios (fecha,nick,contrasena,email,sexo,ip) values ('$fecha','$nick','$contrasena','$email','$sexo','$_SERVER[REMOTE_ADDR]')") ;
echo 'Has sido registrad@. Haz click aquí <a href="index.php">aquí</a> para regresar a la página principal.' ;
}
}
else {
?>
<script>
function revisar() {
if(formulario.nick.value.length < 3) {
alert('El nick debe contener por lo mínimo 3 caractéres.') ;
return false ;
}
if(formulario.contrasena.value.length < 8) {
alert('La contraseña debe contener por lo mínimo 8 caractéres.') ;
return false ;
}
if(formulario.contrasena.value != formulario.c_contrasena.value) {
alert('Las contraseñas no son correctas.') ;
return false ;
}
if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(formulario.email.value)) {
alert('Debes poner un email válido.') ;
return false ;
}
}
</script>
<form name="formulario" method="post" action="<?=$_SERVER[PHP_SELF]?>" onsubmit="return revisar()">
<b>Nick:</b><br>
<input type="text" name="nick" maxlength="20"><br>
<b>Contraseña:</b><br>
<input type="password" name="contrasena" maxlength="10"><br>
<b>Confirmar contraseña:</b><br>
<input type="password" name="c_contrasena" maxlength="10"><br>
<b>Email:</b><br>
<input type="text" name="email" maxlength="40"><br>
<b>Sexo:</b><br>
<select name="sexo">
<option value="0">Masculino
<option value="1">Femenino
</select><br><br>
<input type="submit" name="enviar" value="Registrar">
</form>
</div>
<?
}
?>

4.- Bien, vamos muy bien , ya que tenemos nuestras tablas creadas, nuestro archivo "config.php" y "registrar.php", procederemos a crear nuestri archivo que se encarge de procesar los datos que el usuario introdusca en el formulario "registro.php" .. para eso creamos un archivo llamado "entrar.php" ...

<?
require 'config.php' ;
if($_POST[enviar]) {
function quitar($texto) {
$texto = trim($texto) ;
$texto = htmlspecialchars($texto) ;
# --> Elimina espacios que no pueden ser borrados por trim()
$texto = str_replace(chr(160),'',$texto) ;
return $texto ;
}
$nick = quitar($_POST[nick]) ;
$contrasena = md5(md5(quitar($_POST[contrasena]))) ;
$con = mysql_query("select id,contrasena from usuarios where nick='$nick'") ;
$datos = mysql_fetch_assoc($con) ;
if(mysql_num_rows($con)) {
if($datos[contrasena] == $contrasena) {
setcookie('uid',$datos[id],time()+604800) ;
setcookie('unick',$nick,time()+604800) ;
setcookie('ucontrasena',$contrasena,time()+604800) ;
header("location: $_SERVER[HTTP_REFERER]") ;
}
else {
echo 'La contraseña es incorrecta. Haz click <a href="java script:history.back()">aquí</a> para regresar.' ;
}
}
else {
echo 'El nick no existe. Haz click <a href="java script:history.back()">aquí</a> para regresar.' ;
}
}
?>

5.- Yeahhh , hasta el momento tendremos que tener creadas las tablas en la base de datos y los siguientes archivos:
-> config.php
-> registrar.php
-> entrar.php

Ahora toca el turno de insertar el codigo que nos servira para que los usuarios inicien sesion , por lo general este codigo se inserta en la pagina inicial de la web (esto ya es tu desicion) ...

<?
if(!$_COOKIE[uid]) {
?>
<form method="post" action="entrar.php">
<b>Nick:</b><br>
<input type="text" name="nick" maxlength="20"><br>
<b>Contraseña:</b><br>
<input type="password" name="contrasena" maxlength="20"><br><br>
<input type="submit" name="enviar" value="Iniciar Sesión">
</form>
<p><a href="registrar.php">Nuevo usuario</a>
<?
}
else {
?>
Bienvenid@ <b><?=$_COOKIE[unick]?></b><br><br>
<a href="pagina_protegida1.php">Enlace 1</a><br>
<a href="pagina_protegida2.php">Enlace 2</a><br>
<a href="pagina_protegida3.php">Enlace 3</a><br><br>
<a href="logout.php">Salir</a>
<?
}
?>

NOTA: En el codigo anterior la parte del Enlace 1,2,3 , pueden ser enlaces a secciones que solo los usuarios registrados podran visualizar, ya que esos enlaces solo seran visibles para usuarios que hayan iniciado sesion...


6.-Paciencia .. Ahora creamos el archivo que se encargara de proteger las paginas que nosotros deseemos... (a los usuarios que no esten registrados se les emitira el siguiente mensaje:"Esta sección es sólo para usuari@s registrad@s . [ Registrarse ] --[Iniciar sesion]" .... para hacer eso crearemos otro archivo con el siguiente codigo ... al cual guardaremos como "login.php"

<?
require 'config.php' ;
$con = mysql_query("select count(id) from usuarios where id='$_COOKIE[uid]' and nick='$_COOKIE[unick]' and contrasena='$_COOKIE[ucontrasena]'") ;
if(!mysql_result($con,0,0)) {
exit('<p><b>Esta sección es sólo para usuari@s registrad@s.</b><p><a href="registrarse.php">[Registrarse]</a>') ;
}
?>


7.- Ya casi ..... Procedemos a crear el archivo que servira para que los usuarios registrados cierren sesion y redireccionarlos a la pagina principal del sitio , para eso insertamos el siguiente codigo y lo guardamos como "logout.php"

<?
setcookie('uid') ;
setcookie('unick') ;
setcookie('ucontrasena') ;
header('location: index.php') ;
?>

8.- Por ultimo !!! Solo nos falta proteger las paginas .. OJO, en al paso numero 6 , nosotros creamos el ARCHIVO con el codigo que impedira a los visitantes acceder a las paginas que nosotros deseemos ... Ahora falta invocar ese archivo en cada pagina protegida ...
para invocar el archivo , insertaremos en cada pagina que vayamos a proteger ...el siguiente codigo

<? require 'login.php' ?>


/////////////////////////////////////////////////////////////////////////
Brandon
Have you thought about speakin ENGLISH ?
Andrew
Por favor, hable Inglés SOLAMENTE, este es un foro de habla Inglés. Las reglas dicen, usted debe hablar Inglés!
wozzym
i think he or she tried to create the code is in spanish. thats the problem...but please use http://freetranslation.com
Andrew
QUOTE(wozzym @ Jul 17 2008, 04:44 PM) *
i think he or she tried to create the code is in spanish. thats the problem...but please use http://freetranslation.com

I'd rather use googles translation, it doesn't have that stupid annoying ass "CONGRATULATIONS YOU WON A FREE IPOD/IPHONE/NANO/ASS KICKING"
NaRzY
English translation:
QUOTE
Hello zymic that such a community, I have all the scripts to create a loguin on my page but not where to start, how to mount in our database, here I leave the steps he made to me for help, if someone I can guide please ...

I started ----- -----
1 .- At the outset is basic access to our database and create tables nesesario so that the script is executed correctly.

create table users (
id SMALLINT (5) unsigned not null auto_increment,
int date (10) unsigned not null,
nick varchar (20) not null,
password varchar (32) not null,
Email varchar (40) not null,
COUNTRY varchar (20) not null,
age tinyint (2) unsigned not null,
enum sex ('0 ','1') not null,
Descriptions tinytext not null,
Web varchar (100) not null,
ip varchar (15) not null,
primary key (id)
key (nickname, password)
)

2 .- Once created tables, proceed to create the file called "config.php", which consist of the call to our database, password, user and others ...

<?
unset ($ config);
$ config [1] = 'localhost'; # may be "localhost" but also a URL or IP
$ config [2] = 'chatter'; # user database
$ config [3] = 'password'; # password database
$ config [4] = 'basededatos'; # Name database

$ connect = @ mysql_connect ($ config [1], $ config [2], $ config [3]) or exit ( 'data connection incorrect. ");
mysql_select_db ($ config [4], $ link) or exit ( 'There is no database.');
>



3 .- already taking our charts and created our archive "config.php", proceed to create a form to register users, for it created the following file called "registrar.php"

<?
if ($ _POST [send]) (
require 'config.php';
Remove function ($ text) (
$ text = trim ($ text);
$ text = htmlspecialchars ($ text);
$ text = str_replace (chr (160 ),'',$ text); # Removes spaces that can not be erased by trim ()
return $ text;
)
$ nick remove = ($ _POST [nickname]);
$ email = remove ($ _POST [email]);
with $ = mysql_query ( "select count (id) from where users nick = '$ nickname' or email = '$ email'");
if (mysql_result ($ con, 0.0)) (
echo 'nickname already exists in the database already registered or email. Click <a href="java script:history.back()"> here </ a> to return. " ;
)
else (
$ date = time ();
$ password = md5 (md5 (remove ($ _POST [pass])));
$ remove sex = ($ _POST [sex]);
mysql_query ( "insert into users (date, nickname, password, email, sex, ip) values ( '$ date', '$ nick', '$ password', '$ email', '$ sex','$_ Server [ REMOTE_ADDR ]')");
echo 'You have been registered @. Click here <a href="index.php"> here </ a> to return to the homepage. " ;
)
)
else (
>
<script>
review function () (
if (formulario.nick.value.length <3) (
alert ( 'The nickname must contain at a minimum 3 characters. ");
return false;
)
if (formulario.contrasena.value.length <8) (
alert ( 'The password must contain at a minimum 8 characters. ");
return false;
)
if (formulario.contrasena.value! = formulario.c_contrasena.value) (
alert ( 'Passwords are not correct. ");
return false;
)
if (! / ^ \ w + ([\ .-]? \ w +) * @ \ w + ([\ .-]? \ w +) * (\. \ w (2.4 })+$/. test (Form . email.value)) (
alert ( 'You should put an email valid. ");
return false;
)
)
</ script>
<form name = "form" method = "post" action ="<?=$_ Server [PHP_SELF]> "onsubmit =" return review () ">
<b> Nick: </ b> <br>
<input type="text" name="nick" maxlength="20"> <br>
<b> Password: </ b> <br>
<input type="password" name="contrasena" maxlength="10"> <br>
<b> Confirm Password: </ b> <br>
<input type="password" name="c_contrasena" maxlength="10"> <br>
<b> Email: </ b> <br>
<input type="text" name="email" maxlength="40"> <br>
<b> Sex: </ b> <br>
<select name="sexo">
<option value="0"> Male
Female <option value="1">
</ select> <br> <br>
<input type="submit" name="enviar" value="Registrar">
</ form>
</ DIV>
<?
)
>

4 .- Well, we are going very well, because we have created our tables, our archive "config.php" and "registrar.php" proceed to create nuestri file which is responsible for processing the data to the user in the form Enter " registro.php ".. for that we create a file called "entrar.php" ...

<?
require 'config.php';
if ($ _POST [send]) (
Remove function ($ text) (
$ text = trim ($ text);
$ text = htmlspecialchars ($ text);
# -> Eliminates spaces that can not be erased by trim ()
$ text = str_replace (chr (160 ),'',$ text);
return $ text;
)
$ nick remove = ($ _POST [nickname]);
$ password = md5 (md5 (remove ($ _POST [pass])));
with $ = mysql_query ( "select id, password from users where nick = '$ nick'");
$ data = mysql_fetch_assoc ($ con);
if (mysql_num_rows ($ con)) (
if ($ data [pass] == $ password) (
setcookie ( 'uid', $ data [id], time () +604800);
setcookie ( 'unick', $ nick, time () +604800);
setcookie ( 'ucontrasena', $ password, time () +604800);
header ( "location: $ _SERVER [HTTP_REFERER]");
)
else (
echo 'The password is incorrect. Click <a href="java script:history.back()"> here </ a> to return. " ;
)
)
else (
echo 'The nickname does not exist. Click <a href="java script:history.back()"> here </ a> to return. " ;
)
)
>

5 .- Yeahhh, so far we have to have created the tables in the database and the following files:
--> Config.php
--> Registrar.php
--> Entrar.php

Now is the turn of the insert code that will serve us for users to log, usually this code is inserted into the home page of the site (this is your desicion) ...

<?
if (! $ _COOKIE [uid]) (
>
<form method="post" action="entrar.php">
<b> Nick: </ b> <br>
<input type="text" name="nick" maxlength="20"> <br>
<b> Password: </ b> <br>
<input type="password" name="contrasena" maxlength="20"> <br> <br>
<input type="submit" name="enviar" value="Iniciar Sesión">
</ form>
<p> <a href="registrar.php"> New user </ a>
<?
)
else (
>
Welcome <b> <?=$_ cookies [unick ]?></ b> <br> <br>
<a href="pagina_protegida1.php"> Link 1 </ a> <br>
<a href="pagina_protegida2.php"> Link 2 </ a> <br>
<a href="pagina_protegida3.php"> Link 3 </ a> <br> <br>
<a href="logout.php"> Exit </ a>
<?
)
>

Note: The above code part of the Link 1,2,3 may be links to sections that only subscribers will be able to view, since these links will be visible only to users who have logged ...


6.-Patience .. Now we create the file that is responsible for protecting the pages we want ... (to users who are not registered shall deliver the following message: "This section is only for user @ s @ s record. [Register] - [Login]" .... to do that will create another file with the the following code ... which will save as "login.php"

<?
require 'config.php';
with $ = mysql_query ( "select count (id) from users where id = '$ _COOKIE [uid]' and nick = '$ _COOKIE [unick]' and password = '$ _COOKIE [ucontrasena]'");
if (! mysql_result ($ con, 0.0)) (
exit ( '<p> <b> This section is only to record user @ s @ s. </ b> <a <p> href="registrarse.php"> [Register] </ a>');
)
>


7 .-'re almost ..... Proceed to create the file you serve so that subscribers closed session and redirected to the homepage of the site, for that insert the following code and keep it as "logout.php"

<?
setcookie ( 'uid');
setcookie ( 'unick');
setcookie ( 'ucontrasena');
header ( 'location: index.php');
>

8 .- Finally! Only we need to protect the pages .. EYE, the number 6 step, we create the file with the code that prevents access to visitors to pages that we want ... Now lack invoke that file on every page protected ...
to invoke the file, insert in every page that we will protect the following code ...

<? require 'login.php'?>


////////////////////////////////////////////////// ///////////////////////

Para empezar, por favor, sólo hablan Inglés en este foro.
En segundo lugar, utiliza el [code] etiquetas para envolver en su código para hacer las cosas un poco neater.
Si usted no puede hablar con fluidez Inglés, por favor alguien que pueda.

Jacob.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.