How to Create Login Page in PHP/MySQL

Related code: How to Create Secure Login Page in PHP/MySQL. Yesterday I posted a tutorial on how to create a registration page using PHP/MySQL. To make some follow up with my registration page tutorial, I decided to create another tutorial on how to create a login page using PHP/MySQL. The Features of my login page contain input validation using PHP session. One unique feature also with my login page is the logout function, it is unique because unlike with other login page once the user click the logout button and click the back button of the browser, their system allows the user to go back as if it still logged in, which is not appropriate for security reason. But here in my login page once the user click the logout button, the user can no longer go back to their previous page. The only way to go back to the previous page is to login again. To start this tutorial let’s follow some steps below.

Creating Our Database

First we are going to create our database which stores our data. To create a database: 1. Open phpmyadmin 2. Click create table and name it. 3. Then name the database as "simple_login". 4. After creating a database name, click the SQL and paste the following code.
  1. CREATE TABLE IF NOT EXISTS `member` (
  2.   `mem_id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `username` varchar(30) NOT NULL,
  4.   `password` varchar(30) NOT NULL,
  5.   `fname` varchar(30) NOT NULL,
  6.   `lname` varchar(30) NOT NULL,
  7.   `address` varchar(100) NOT NULL,
  8.   `contact` varchar(30) NOT NULL,
  9.   `picture` varchar(100) NOT NULL,
  10.   `gender` varchar(10) NOT NULL,
  11.   PRIMARY KEY (`mem_id`)
  12. ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Creating Our Form

Next step is to create a form and save it as index.php. To create a form, open your HTML code editor and paste the code below in the upper part of the document or above the html tag. The code below is use to disallow the user to go back as if it still logged in.
  1. <?php
  2.         //Start session
  3.         session_start();       
  4.         //Unset the variables stored in session
  5.         unset($_SESSION['SESS_MEMBER_ID']);
  6.         unset($_SESSION['SESS_FIRST_NAME']);
  7.         unset($_SESSION['SESS_LAST_NAME']);
  8. ?>
Paste the code bellow after the body tag of the HTML document
  1. <form name="loginform" action="login_exec.php" method="post">
  2. <table width="309" border="0" align="center" cellpadding="2" cellspacing="5">
  3.   <tr>
  4.     <td colspan="2">
  5.                 <!--the code bellow is used to display the message of the input validation-->
  6.                  <?php
  7.                         if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
  8.                         echo '<ul class="err">';
  9.                         foreach($_SESSION['ERRMSG_ARR'] as $msg) {
  10.                                 echo '<li>',$msg,'</li>';
  11.                                 }
  12.                         echo '</ul>';
  13.                         unset($_SESSION['ERRMSG_ARR']);
  14.                         }
  15.                 ?>
  16.         </td>
  17.   </tr>
  18.   <tr>
  19.     <td width="116"><div align="right">Username</div></td>
  20.     <td width="177"><input name="username" type="text" /></td>
  21.   </tr>
  22.   <tr>
  23.     <td><div align="right">Password</div></td>
  24.     <td><input name="password" type="text" /></td>
  25.   </tr>
  26.   <tr>
  27.     <td><div align="right"></div></td>
  28.     <td><input name="" type="submit" value="login" /></td>
  29.   </tr>
  30. </table>
  31. </form>

Creating our Connection

Next step is to create a database connection and save it as "connection.php". This file is used to connect our form to database.
  1. <?php
  2. $mysql_hostname = "localhost";
  3. $mysql_user = "root";
  4. $mysql_password = "";
  5. $mysql_database = "simple_login";
  6. $prefix = "";
  7. $bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
  8. mysqli_select_db($bd, $mysql_database) or die("Could not select database");
  9. ?>

Writing Our Login Script

Next step is to create our login script that validates our input data and save it as login_exec.php.
  1. <?php
  2.         //Start session
  3.         session_start();
  4.  
  5.         //Include database connection details
  6.         require_once('connection.php');
  7.  
  8.         //Array to store validation errors
  9.         $errmsg_arr = array();
  10.  
  11.         //Validation error flag
  12.         $errflag = false;
  13.  
  14.         //Function to sanitize values received from the form. Prevents SQL injection
  15.         function clean($str) {
  16.                 echo "str: ".$str;
  17.                 $str = @trim($str);
  18.                 if(get_magic_quotes_gpc()) {
  19.                         $str = stripslashes($str);
  20.                 }
  21.                 return mysqli_real_escape_string($str);
  22.         }
  23.  
  24.         //Sanitize the POST values
  25.         $username = $_POST['username'];
  26.         $password = $_POST['password'];
  27.  
  28.         //Input Validations
  29.         if($username == '') {
  30.                 $errmsg_arr[] = 'Username missing';
  31.                 $errflag = true;
  32.         }
  33.         if($password == '') {
  34.                 $errmsg_arr[] = 'Password missing';
  35.                 $errflag = true;
  36.         }
  37.  
  38.         //If there are input validations, redirect back to the login form
  39.         if($errflag) {
  40.                 $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
  41.                 session_write_close();
  42.                 header("location: index.php");
  43.                 exit();
  44.         }
  45.  
  46.         //Create query
  47.         $qry="SELECT * FROM member WHERE username='$username' AND password='$password'";
  48.         $result=mysqli_query($bd, $qry);
  49.  
  50.         //Check whether the query was successful or not
  51.         if($result) {
  52.                 if(mysqli_num_rows($result) > 0) {
  53.                         //Login Successful
  54.                         session_regenerate_id();
  55.                         $member = mysqli_fetch_assoc($result);
  56.                         $_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
  57.                         $_SESSION['SESS_FIRST_NAME'] = $member['username'];
  58.                         $_SESSION['SESS_LAST_NAME'] = $member['password'];
  59.                         session_write_close();
  60.                         header("location: home.php");
  61.                         exit();
  62.                 }else {
  63.                         //Login failed
  64.                         $errmsg_arr[] = 'user name and password not found';
  65.                         $errflag = true;
  66.                         if($errflag) {
  67.                                 $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
  68.                                 session_write_close();
  69.                                 header("location: index.php");
  70.                                 exit();
  71.                         }
  72.                 }
  73.         }else {
  74.                 die("Query failed");
  75.         }
  76. ?>

Creating Our Authentication File

Next step is to create our authentication file and save it as auth.php. this code is use to disallow the user to go back as if it still logged in.
  1. <?php
  2.         //Start session
  3.         session_start();
  4.         //Check whether the session variable SESS_MEMBER_ID is present or not
  5.         if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
  6.                 header("location: index.php");
  7.                 exit();
  8.         }
  9. ?>

Creating Our Home page

Next step is to create a homepage and save it as home.php.
  1. <?php
  2.         require_once('auth.php');
  3. ?>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  8. <title>Untitled Document</title>
  9. <style type="text/css">
  10. <!--
  11. .style1 {
  12.         font-size: 36px;
  13.         font-weight: bold;
  14. }
  15. -->
  16. </style>
  17. </head>
  18.  
  19. <body>
  20. <p align="center" class="style1">Login successfully </p>
  21. <p align="center">This page is the home, you can put some stuff here......</p>
  22. <p align="center"><a href="index.php">logout</a></p>
  23. </body>
  24. </html>
That’s all you have already created your login page with unique features. Hope this code will help you, see you guys in my next tutorial. We've created a more secure registration and login page using CodeIgniter and Ion Auth. We highly recommend you use this instead if you want to secure your site. However, we're using CodeIgniter framework on this. If you are interested, kindly visit Secure Registration and Login Script with PHP and MySQL using CodeIgniter and Ion Auth.

Comments

sir,your code is well and good...but i have one doubt..mytask is that to create the login page..database member can log in to my login page..after log in,the member who would logged in details will be shown..that member can edit that details..after finished edit process to press the finish button..again the loginpage will be open..after that member can logged out..please send the source code for above task..this is my mail id:[email protected]

ur code real help me thanx.....

its very nice

hi...thanks alot for your very useful code But, how can I show the user profile(fname,lname,...) in the home page after the validation?

GOD is so great of your life . It works! Keep up the good work and GOD BLESS :)

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /mrdthome/webwalk/public_html/admin/login_exec.php:1) in /mrdthome/webwalk/public_html/admin/login_exec.php on line 3 Query failed

In reply to by Anonymous (not verified)

I removed the white space and upload the files. Now i am getting the result of Query failed. What mistake i have done? Hence it works without errors on localhost.

In reply to by Sakthi Nagarajan (not verified)

Change the error_reporting in your php.ini to: error_reporting = E_ALL & ~E_NOTICE

Im a biginer for web but I dne well hahah thnks lot

cool, dude!!

Fatal error: Call to undefined function get_magic_quotes_gpc() in C:\AppServ\www\myphp\login_exec.php on line 19

Page1:login.php
<?php
session_start();
mysql_connect("localhost","root","") or die("error connect");
mysql_select_db("task2") or die(" error database");
$email=$_POST['email'];
$pass=$_POST['password'];
$login=mysql_query("SELECT * FROM login WHERE email='$email' AND password='$pass'");
$sql=mysql_num_rows($login);
if($sql!=0){
$_SESSION['email']=$email;
header('Location: login_verify.php');
}
else {
echo "Wrong Username or Password";
}
?>
page2:login_check.
<?php
session_start();
if(isset($_SESSION['email'])){

echo "<center><h1>".$_SESSION['email']."Welcome to Home page</h1></center>";
}
else{
header('Location: login_im.php');
}
?>
<a href="newlogout.php">Logout</a>
page3:logout.php
<?php
session_start();
session_destroy();
header("location:/login_im.php");
?>

excellent! thank you very much!

I'm new to this things of web designing I want to know how can a create a table in my database on-line, like the way is being done on a localhost.

Unbelievable!!! I tried over and over many of Tutorials and every time i was not successful,but IT IS WORKING Thank you so much

how to connect VB.net to SQL Server2005 provide source code plz

Hi, The login script works, but I'm not sure how the logout script should work. I was expecting a Logout button somewhere. Also, in the login script. 1) the password shows when it is typed in. Is there a way to just show ****** instead? 2)This code in the index.php shows as comment. Not sure why. 0 ) { echo '
    '; foreach($_SESSION['ERRMSG_ARR'] as $msg) { echo '
  • ',$msg,'
  • '; } echo '
'; unset($_SESSION['ERRMSG_ARR']); } ?> Otherwise, it's great.Thanks.

The tutorial and codes above is really helpful to me. Thank you very much.

Your code is perfect! Thank you very much!

Hey great work there: but one more question: what i want want only a logged in person to view all the other pages??

how to add pdf file in database through php form at admin side

how if iwant to add selection..two text area and 1 selection... how to write for selecetion???hope someone can help me...

its very good tutorial .. i just copy and paste and its run .. thanks alot...

can anyone help me or can show me codes on how to create a login. i have 2 tables in my database namely: "users" and "roles". a user should login by their corresponding roles. how can it be done? or is it possible that way? pls help me asap. Thank You.

your sourcecodes are very useful. i've got a project and it includes logging in. I have many types of admin: 1) admin that has a FULL ACCESS of the system, 2) admin that has a limited access only, and 3) admin that has a lesser access than the second one. Member users also has a limitted access to my information portal project. i have tables in my database namely: "users(user_id,user_name,password)", "users_data(data_id, lname, fname, mname, email)", "roles(role_id,role_type)". My Problem is that, how will it be when a USER will login, he will be redirected to its corresponding page(according to its role type). and so with the other users. please help me with this one. Please send me your sourcecode for this at [email protected]. thank you in advance!

Thanks man,i like this,it worked well with me.

Hello Sir,
I'm also try to develop login system.I'm new in PHP.Please send me complete login system for my reference if possible.my email-id is:[email protected] .

thank u very much............ really helped me lot....... thanks

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\manjul\connectivity\students\simple_db\login_exec.php:4) in C:\xampp\htdocs\manjul\connectivity\students\simple_db\login_exec.php on line 44

its working but its not given error when the password and username dont match it just logs them need help

how do you link this to your html page ?

how to change my password visibility to ********

Add new comment