How to Create Login Page in PHP/MySQL

Submitted by: 
Visitors have accessed this post 1307596 times.

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.

  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`)

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. //Unset the variables stored in session
  4. unset($_SESSION['SESS_MEMBER_ID']);
  5. unset($_SESSION['SESS_FIRST_NAME']);
  6. unset($_SESSION['SESS_LAST_NAME']);
  7. ?>

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
  4. //Include database connection details
  5. require_once('connection.php');
  7. //Array to store validation errors
  8. $errmsg_arr = array();
  10. //Validation error flag
  11. $errflag = false;
  13. //Function to sanitize values received from the form. Prevents SQL injection
  14. function clean($str) {
  15. echo "str: ".$str;
  16. $str = @trim($str);
  17. $str = stripslashes($str);
  18. }
  19. }
  21. //Sanitize the POST values
  22. $username = $_POST['username'];
  23. $password = $_POST['password'];
  25. //Input Validations
  26. if($username == '') {
  27. $errmsg_arr[] = 'Username missing';
  28. $errflag = true;
  29. }
  30. if($password == '') {
  31. $errmsg_arr[] = 'Password missing';
  32. $errflag = true;
  33. }
  35. //If there are input validations, redirect back to the login form
  36. if($errflag) {
  37. $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
  38. header("location: index.php");
  39. exit();
  40. }
  42. //Create query
  43. $qry="SELECT * FROM member WHERE username='$username' AND password='$password'";
  44. $result=mysqli_query($bd, $qry);
  46. //Check whether the query was successful or not
  47. if($result) {
  48. if(mysqli_num_rows($result) > 0) {
  49. //Login Successful
  50. $member = mysqli_fetch_assoc($result);
  51. $_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
  52. $_SESSION['SESS_FIRST_NAME'] = $member['username'];
  53. $_SESSION['SESS_LAST_NAME'] = $member['password'];
  54. header("location: home.php");
  55. exit();
  56. }else {
  57. //Login failed
  58. $errmsg_arr[] = 'user name and password not found';
  59. $errflag = true;
  60. if($errflag) {
  61. $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
  62. header("location: index.php");
  63. exit();
  64. }
  65. }
  66. }else {
  67. die("Query failed");
  68. }
  69. ?>

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. //Check whether the session variable SESS_MEMBER_ID is present or not
  4. if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
  5. header("location: index.php");
  6. exit();
  7. }
  8. ?>

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" "">
  5. <html xmlns="">
  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>
  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.


Please someone should tell me what's the user Name and Password for the log in

Great stuff. need this for my web app project.

Great stuff, i cannot wait to trial it out

please send the php code for ...nursery management system...on this email->
[email protected]

your code very good for me.
Thank you.

hi, good afternoon po, medyo may napansin lang po ako, panu po ba gawin ung pag ibinack mo sya ay dapat wala ng makikitand username at password?

Thanks for that, I have been looking around the net and most places want you to signup just to see the code. This works great. If anyone is having issues, all you need to do is follow each step.

I created it well but the password it doesn't hide. How can I do it so that I can hide it?

many thanks for this tutorial .... this was simple and applicable.

I want to create registration form n from tat username n password mentioned in registration I want to login..
so please help me out in this as quick as paossible............
very useful source code

once I log user out he can relog in by using back arrow navigation.when I include the hath.PHP in my home.PHP nothing is happening when user login details are inserted

Argie I have ceated th page it asking username and password, but dont have [email protected], its giving message " could not connect data base"

what is the solution?

Argie I have a different issue...I made login,index,home,connection,auth.php and transfer it to server folder, this folder contain website files, also In server I created database paste the sql code.......but how it will run? your help/answer will be highly appreciated, because i am a beginner, plz urgently, [email protected]

i am riham
how to hide password in password text box????
pls help me


please i need support
thank you

this is by far the best sample login Ive used, thanks for sharing

true but this code is too lenthy and difficult

i want a feed back form and its comments and the name of the person who comments are shows in bellow the space

I will try this soon. Please, I will need similar in PHP on online students examinations in five subjects(computer science, chemistry, biology and physics) with instant result at the end of exams.

thanks you for your explore

$_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];

56. $_SESSION['SESS_FIRST_NAME'] = $member['username'];

57. $_SESSION['SESS_LAST_NAME'] = $member['password'];

58. session_write_close();

Names don't match!!

Nice tutorial ... but missing a register page can someone help me to make it. or someone is make reg page for this tutorial :D Thanks for sharing.

can you please help in next previous, last and first buttons in php/mysql

hi dear i just wanna to say thank you ..i was desperately wanted this information

god bless you


Thanks Man! Be blessed

Am starting to work on it.....i know twill work

It is very impotant thankes to much

I installed and everything is working smoothly.
Thank you very much for sharing such a great tool and explanation.

Cant say awesome to learn

Amit ombale

its saying ....Query Failed ....wats up

Hello Thank You So Much For Detailed Explanation

thanks it help me a lot

this really helped me, thanks.

thanks for this code fully running

I am getting output query failed .plz tell me where i am wrong

Nice codes. It worked for me :)

How i will update my sql table from home.php please help me with code

it is too easy and awesome ....

I think it should be like

  1. $_SESSION['SESS_FIRST_NAME'] = $member['fname'];
  2. $_SESSION['SESS_LAST_NAME'] = $member['lname'];

this code is ver useful

Is a simple and clean code.Easy to follow and understand.

Attach the source code in zip and upload it for us to download please

IT Guru.

i want to update my data..after updating when i click button automatically it moves to logout page..i dont know what to do..i checked localhost it works perfectly but after upload into server it create problem

How can i stop guest user to view List-page ( all records )in my database tables.
Guest user should see only record by search criteria.
Guest user should not see the list of all records in some table.

ur codeis superb help in log out code

It give error that database could not be selected... please tell which database is selected

i got an error message. please help me to clarify
Warning: Cannot modify header information - headers already sent by (output started at C:\AppServ\www\an\connection.php:19) in C:\AppServ\www\an\login_exec.php on line 68

sir, can u give me the username and password.. my email id is [email protected]

nice ,,,,,,,,,,,,,,,, goo job

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


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.