Login php


By Rodrigo

Created 2014-07-05 05:28:14 Modified 2015-04-06 21:26:11

Login is the process by which it controls users access, sometimes only a login without access control to the application, I mean without groups; administrators, managers, basic users, etc... when the administrators have more permissions than managers, you may have a standalone application login or a web login which uses sessions variables, that's the point about this tutorial

In this tutorial we are going to develop a php login using the session variables

this tutorial was written using the following gear:

  • Hardware:           laptop Thinkpad E430 Intel I5, 4gb Ram, 500gb HDD
  • OS:                    x86_64 GNU/Linux Ubuntu 14.10
  • Kernel:               3.13.0-29-generic
  • IDE/Text editor:   Zend Eclipse for PHP Developers
  • PHP:                   PHP 5.4.16 (cli) (built: Jun 24 2013 12:08:02) 
  • DB:                     Mysql 5.5.31
  • Mysql client:        PhpMyadmin
  • Browser:             Chromium Version 34.0.1847.116 Ubuntu 14.04 aura (260972)


1.- Creating the db:

First we need a database to work on the login process, let's take the following script and run it on mysql

USE tutorial;
   name VARCHAR(45) NOT NULL,
   birthdate DATE NOT NULL,
   password VARCHAR(45) NOT NULL
INSERT INTO users(name, birthdate, password)VALUES('Ocelot', '1944-06-06','revolver');

2.- Creating the index page:

Once created the database we can create our index.php which uses the previous data, let's create these following pages into the folder phplogin (create it under your "www", or "htdocs" folder if you're using apache)

//we put the below code to work with php sessions
//now we validate if the session->usuario variable is within
//if not we redirect to login form
  header('Location: login.php'); 
  <h1>Welcome <?php echo $_SESSION['usuario']?></h1>
  <a href="logout.php">Logout</a>

3.- Creating the login page:

This is only the login form login.php

<form action="validar_usuario.php" method="post">
   <td><input name="admin" required="required" type="text" /></td>
   <td><input name="password_usuario" required="required" type="password" /></td> 
   <td colspan="2"><input name="iniciar" type="submit" value="Login" /></td>

4.- Creating the validation page:

This is the validation page, this page validates the data and redirect to the success page or login again

//db connection
mysql_connect('','root','root')or die ('Ha fallado la conexión: '.mysql_error());
mysql_select_db('tutorial')or die ('Error al seleccionar la Base de Datos: '.mysql_error());
$usuario = $_POST["admin"];//variables from the form
$password = $_POST["password_usuario"];
//first we do the query for find the user, then we compare the passwords
$result = mysql_query("SELECT * FROM users WHERE name = '$usuario'");
if($row = mysql_fetch_array($result))
//if the user exists then we compare the passwords
 if($row["password"] == $password)
  //We save the $user variable (could be an object) in the session variable usuario
  $_SESSION['usuario'] = $usuario;  
  header("Location: index.php");  
   <script languaje="javascript">
    alert("Incorrect password");
    location.href = "login.php";
//incorrect username
 <script languaje="javascript">
  alert("Incorrect username");
  location.href = "login.php";

//Mysql_free_result() se usa para liberar la memoria empleada al realizar una consulta

/*Mysql_close() se usa para cerrar la conexión a la Base de datos y es 
**necesario hacerlo para no sobrecargar al servidor, bueno en el caso de
**programar una aplicación que tendrá muchas visitas ;) .*/

5.- Creating the logout page:

This code just destroys the session and redirects you to the login

 $_SESSION = array();
 //we destroy the session
 header("location: login.php");

6.- Login:

up to this point, we are done, now let's go to the index page and see what happens go to, you'll see the following page

let's login typing ocelot and password revolver


if things go well, you get to the index page, otherwise you'll see the alert error




Download it in https://drive.google.com/file/d/0BwOqSob-RrBOaGpwRk9RRGJPN2M/edit?usp=sharing

7.- Conclusion:

Login, permissions and restricted areas are always necessary in a website or a shared application, you should have administrators and non administrators to handle the website properly

8.- Reference links:

comments powered by Disqus