Loading

How to Create Login Page in PHP/MySQL

Submitted by: 
Language: 
Visitors have accessed this post 865974 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.

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

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" "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.




Comments

Your code was very useful. Thank you.

But, how can I show the username in the home page after the validation?

You can display the username by adding something like this:
}else{
echo"Welcom " .$_POST['username'];
}
after fetching the row i.e $sql=mysql_num_rows($query);
Thank you

on which page should i put this codes

This helps me alot thank you

Thanks Argie. Your article has helped me a lot. Such a error-less code is what a fresher looks for. Well written n well explained. Thanks buddy.- Mahesh

Gosh, another beautiful tutorial. Appreciate the work. Thank you xxxx

thankyou verymuch..the only tutorial worked after trying tons of tutorials...really thankyou....

This tutorial seems really easy to follow but I get the following message when I copy and past into sql
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1.CREATE TABLE IF NOT EXISTS `member` (2. `mem_id` int(11) NOT NULL AUTO_INCREM' at line 1

I dont know what the problem is with the syntax for my version which is 5.0.91-log
Can you help? sorry am a total newbie and this is probs really easy.

Take out the leading line numbers. Example:
1.CREATE ... should be CREATE ...

hi
thanks a lot.
Ur code is very useful bt can you provide the validations to this form

realy useful source codes.

super thank you to the creator of this program...
this really helps a lot...thank you!!!

i need urgent....,

why i cant connect to database sir ?

You have made my day! thanks :) everything is working for me.

Your codes needs to be updated!

Big thanks for the registration and login scripts, i've just implemented both and they work beautifully (after initial confusion with double index pages heh) - definately the most simple/logical tutorial to follow on this topic ive seen

your code very useful ,but if i want to validate the registration form ,that is why a unique "username" will save or it already used
echo "This UserName is already used. Please try another username"
what can i do ????????????? please help me
my E_mail - "uddin.mohi16@yahoo.com" I already use your code it is useful.thanks,

errors,errors errors.....

"Warning: session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent in /Applications/XAMPP/xamppfiles/htdocs/xampp/example/section2/sec1/login_exec.php on line 53

Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/xampp/example/section2/sec1/connection.php:2) in /Applications/XAMPP/xamppfiles/htdocs/xampp/example/section2/sec1/login_exec.php on line 59"

help please!!!

what will be the input for the login form and how to incorporate the same in the backend?main issues are not there.disgusting.

thank you!! this tutorial helped me a lot :)

user name and password not found-- am getting this error after i login.
i already edited the connection.php. below is my code.. thanks in advance.

$mysql_user = "myusername";
$mysql_password = "mypassword";
$mysql_database = "besthome_simple_login";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
??>

am getting "Could not select database"
please help.. thanks in advance

$mysql_user = "my_user";
$mysql_password = "mypassword123";
$mysql_database = "mydatabase";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
??>

$mysql_user = "my_user";
$mysql_password = "mypassword123";
$mysql_database = "mydatabase";
$mysql_hostname = "localhost";
$conn = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $conn) or die("Could not select database");

•user name and password not found

Logged out. Clicked on back. No login page. Logging in directly.

easy to understand

This was really helpful but I have noticed that the password is not case sensitive which obviously limits security. I don't know if it is my mysql database settings or the actual login script that is the problem

good explore

how do i create user and passwords who will login into then system after the login page creation

how to create web services in login page php and mysql.
please help me.
thank u.

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampplite\htdocs\index.php:1) in C:\xampplite\htdocs\index.php on line 3

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampplite\htdocs\index.php:1) in C:\xampplite\htdocs\index.php on line 3

i have also same Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent

if you have any answer please help me.
vikasgenus@gmail.com

Thank you

thanks dude, it works

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: NO) in C:\xampp\htdocs\BloodBank\connetion.php on line 6
Could not connect database

Line 6 in connection...
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");

Plz help me.

hi...first you should create your database and create your user in your database with password then in connection.php follow:

$mysql_user = "your user that you are creating in your database";
$mysql_password = "your user password that you are creating in your database";
$mysql_database = "your database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
??>
if you have any question contact me with my email:
a.kargaran_d@yahoo.com

$mysql_hostname =""; what should come here

If you would like to obtain a good deal from this paragraph then you have to apply these techniques to your won web site.

There is just a small error. The query should be "SELECT COUNT(*) FROM tablename WHERE..." instead of whatever you wrote Argie. Except that, everything else is fine.

There is just a small missing detail. The query should be "SELECT COUNT(*) FROM tablename WHERE..." instead of whatever you wrote Argie. Except that, everything else is fine.

hello, i'm Ameh james...thanks for this tutorial.
however when i tried it, on the web page after clicking the login button...i get this error message:
"Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\test\links\login.php on line 13
Sorry, there is no username John with the specified password.Try again"
"John" is what i have in the database. please i need help

Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\test\REG1\login_exec.php:11) in D:\xampp\htdocs\test\REG1\login_exec.php on line 70

it is nice tutorial but where i found the username and password?

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:seenu1692@gmail.com

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

Your code is very good but can you help me code for log out? my mail is abdhank@gmail.com

Pages

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.

Filtered HTML

  • You may insert videos with [video:URL]
  • 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.
To prevent automated spam submissions leave this field empty.