PHP Login Page Example.
Wall Script
Follow Me:
Thursday, September 24, 2009

PHP Login Page Example.

Are you looking for PHP login script, in this post I want to discuss how to create a simple PHP login with welcome page using MySQL database. This will explain you creating user tables, posting form values and storing and destroying the session values. If you are a PHP beginner take a quick look at this live demo with Username : test Password : test. This post has been updated with mysqli.


PHP Login Page Example



Download Script     Live Demo

New Tutorials: Ajax Login Page with Shake Effect and PHP Login System with PDO Connection.

Database
MySQL admin table columns id, username, passcode.
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE,
passcode VARCHAR(30)
);



Password Encryption PHP Login Script with Encryption.

Config.php
Database configuration file.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

New Tutorial: PHP Login Script with Encryption.

Login.php
Contains PHP and HTML code.
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myusername=mysqli_real_escape_string($db,$_POST['username']);
$mypassword=mysqli_real_escape_string($db,$_POST['password']);
$passwordSecure=md5($mypassword);
$sql="SELECT id FROM admin WHERE username='$myusername' and passcode='$passwordSecure'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$active=$row['active'];
$count=mysqli_num_rows($result);


// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
session_register("myusername");
$_SESSION['login_user']=$myusername;

header("location: welcome.php");
}
else
{
$error="Your Login Name or Password is invalid";
}
}
?>
<form action="" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Submit "/><br />
</form>

lock.php
Session verification. If no session value page redirect to login.php
<?php
include('config.php');
session_start();
$user_check=$_SESSION['login_user'];

$ses_sql=mysqli_query($db,"select username from admin where username='$user_check' ");

$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

$login_session=$row['username'];

if(!isset($login_session))
{
header("Location: login.php");
}
?>


welcome.php

<?php
include('lock.php');
?>
<body>
<h1>Welcome <?php echo $login_session; ?></h1>
</body>


logout.php
SignOut Destroy the session value.
<?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


248 comments:

  1. Very useful post.
    Thanks

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Your session checking not very secure.

    ReplyDelete
  4. Thanks! Very helpful!

    ReplyDelete
  5. A few hints:
    – Using addslashes() for escaping is bad practice
    – Storing passwords unencrypted is bad practice
    – session_register() is deprecated
    – A valid location headers require a full URL
    – lock.php makes no sense. The existence of a username and / or user ID in the session is sufficient, if the authentication was done properly. (Unless you want to check for every single request if a user account has been disabled or deleted.)

    ReplyDelete
  6. something is one word

    ReplyDelete
  7. As Anonymous said, it's not good practice to store user passwords in a database in cleartext.

    ReplyDelete
  8. go to this site they have a tutorial on how to creat a simple login registration php

    http://dudes-online.zxq.net/viewtopic.php?f=2&t=2

    ReplyDelete
  9. Plain text pass-wording != good idea. Use MD5 (varchar[32]) or SHA1 (varchar[40])

    ReplyDelete
  10. Yes I agree. We need to encrypt the password.

    ReplyDelete
  11. THank You very much
    It really helped

    ReplyDelete
  12. why you place double check is it neccessary on that place . on welcome page include. instead of that placing if(!$_SESSION['login_user']):
    gogto login page

    ReplyDelete
  13. nice work..thanks

    ReplyDelete
  14. nice work....very helpful for the beginners....

    ReplyDelete
  15. great code, I love this one

    ReplyDelete
  16. Thanks man, for this post it was life saving ....
    put more

    ReplyDelete
  17. wwoowwww.........
    thanks budddyyy..........perfect
    uuummmmaaaahhhhhhhhhh......on ur cheek :)

    ReplyDelete
  18. Nice little script Srinivas! The session part is nice & clean.

    Ta!

    ReplyDelete
  19. Thanks it's very useful .., please add the many sample examples.

    ReplyDelete
  20. very helpfulll...........great...

    ReplyDelete
  21. i have tried your entire script
    but getting an error

    1.mysql_fetch_array() expects parameter 1 to be resource, boolean given

    2.mysql_num_rows() expects parameter 1 to be resource, boolean given


    plz help with dis asap

    ReplyDelete
  22. Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'@'localhost' (using password: YES) in C:\xampp\htdocs\login\config.php on line 7
    Opps some thing went wrong



    guys can you please help me with this erroe??

    ReplyDelete
  23. TNKS YOU VERY MUCH....!!!!!!!!!!!!!!!!!!!!!

    ReplyDelete
  24. Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'@'localhost' (using password: YES) in C:\xampp\htdocs\login\config.php on line 7
    Opps some thing went wrong



    guys can you please help me with this error??

    ReplyDelete
  25. @yu You need to create a database and use the username and password you used for that to connect to the database. Just using what is already there won't do anything as you found out (unless you did use the username root and password yes)

    ReplyDelete
  26. 1. don't store passwords, use an md5 hash or better
    2. salt passwords before you create the hash
    3. store users, salt and password in different tables, where only a limited php page and limited mysql user can verify the login
    4. validate input always, unless its trusted
    5. use mysql procedures for ckecking user
    6. encrypt salt, note that this is ok but almost useless
    7. if your brave, and have a good memory, use 100% unique sql tables and fields..i.e.
    zu53Rs, xP4s5w0rds, y541ts
    zuSERs, xPAsSwOrds, ySAlts

    ReplyDelete
  27. Not a bad little login example. Most examples don't use SESSIONS. Your example isn't perfect, but with a few tweaks it isn't bad now.

    1) You should encrypt passwords.

    2) On a few of the php files, the session_start() was not the FIRST line of code. Thus causing a error entry in the error_log. So ensure session_start(); is the VERY VERY VERY first line of code in each file that it is in!

    3) Also, another minor error creating an entry in error_log. It is because on when a user isn't logged in, the session variable is null/nothing/empty... And you don't check if it is empty, you just assume there is a value and perform a database query with an empty username.

    Lock.php:

    session_start();
    if(!isset($_SESSION['login_user'])){
    header("location:login.php");

    ReplyDelete
  28. there is an error on the first line of login.php - youve writetn >?php instead of <?php

    ReplyDelete
  29. thanks for the sample login program...

    it helped to anlyze where i went wrong..

    thanks again.. im adding your site to ma favourite list.. keep up the good work buddy...:)

    ReplyDelete
  30. Hello, i find some problems with your "Login.php"

    >?php

    it should be

    <?php

    ReplyDelete
  31. very good post
    its usefull form me
    Ashish

    ReplyDelete
  32. lock.php something wrong hah?
    Confused -,-

    ReplyDelete
  33. What is this yaar ?
    Dis is not work.....
    Plz solve this error....

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\Saipro School\login.php on line 12

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\Saipro School\login.php on line 14

    ReplyDelete
  34. Doesnt work!!

    Errors so far...

    Notice: Undefined index: active in C:\wamp\www\Project1\Login.php on line 16

    Deprecated: Function session_register() is deprecated in C:\wamp\www\Project1\Login.php on line 25

    ReplyDelete
  35. this code is very useful for all php programmers...

    ReplyDelete
  36. I am a little confused on the if ($count) statement

    you set it equal to 1 but my count never is = 1 so it always just displays the ERROR msg.
    What do you mean when you say table row must be 1 row??

    ReplyDelete
  37. Notice: Undefined index: active in C:\wamp\www\login.php on line 17

    Fatal error: Call to undefined function session_register() in C:\wamp\www\login.php on line 25

    kidly solve

    ReplyDelete
  38. Thanks. Helpful!!!

    ReplyDelete
  39. Really easy 4 unnderstand...thanx....

    ReplyDelete
  40. good i can make use of this pieces of codes

    ReplyDelete
  41. I write bad angel, but hope you understand.
    This script works, but it does not lock the sides to be protected.
    What should be in the pages to be protected?
    I tried with.

    When opened page before Login

    ReplyDelete
  42. session_start();
    if(!isset($_SESSION['login_user'])){
    header("location:login.php");}

    thanks for the lock.php code

    from anonymous posted june 25 2011

    ReplyDelete
  43. nice code, it helps more

    ReplyDelete
  44. 22 yar sira code hai
    ......
    awesmmm code 22 g......

    ReplyDelete
  45. i have one problem with this code, when i submit a login form page just reload and doesnt redirect to the header location.

    ReplyDelete
  46. thankssssssssssssssssssss

    ReplyDelete
  47. AM going to see if it is helpful. thx!

    ReplyDelete
  48. Thanks
    Your tutorial was like a pain killer for my headache.
    please post more articles.

    Thanks

    ReplyDelete
  49. very useful for me as I am a beginner in PHP

    ReplyDelete
  50. great tutorial! helped me make my first steps in a new language.

    ReplyDelete
  51. Nice... Thanks...

    ReplyDelete
  52. can u please provide the same code for users login.
    thanks in advance

    ReplyDelete
  53. nice post and thanks.its very useful for the students those who are doing live project.thanq sir......

    ReplyDelete
  54. hi,

    thanks for the tutorial...i encounter some difficulties...when i try to enter a wrong password it didnt comes out the warning message "Your Login Name or Password is invalid"

    thanks

    ReplyDelete
  55. thanks! and too much easy code..

    ReplyDelete
  56. Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\xampp\testingan\login.php on line 12

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\xampp\testingan\login.php on line 14

    ReplyDelete
  57. Thanks ,,,,,,,,, really helped me out.

    ReplyDelete
  58. it was a nice post ....
    but i m getting a error

    in "welcome.php"

    $login_session; is undefined variable;

    ReplyDelete
  59. Thanks...this will be helpful for beginners.

    ReplyDelete
  60. thanks for help

    ReplyDelete
  61. your not setting or retrieving the sesstions

    ReplyDelete
  62. It's very nice post,and specially it's good for beginners...
    thanks a lot...

    ReplyDelete
  63. Superb... Thanks Man...

    ReplyDelete
  64. Hello, Your script is awesome!

    Can you tell me how to session time out automatically if page is idle.


    thanks

    ReplyDelete
  65. i have error came out..
    Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\guardall\login.php:8) in C:\xampp\htdocs\guardall\login.php on line 32

    Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\guardall\login.php:8) in C:\xampp\htdocs\guardall\login.php on line 32

    ReplyDelete
  66. nice code...........it is very very helpful to me

    ReplyDelete
  67. You are simply superb, expecting more useful articles from you

    --ATM

    ReplyDelete
  68. am a newbie..thnx ..ths isht's clear n precise

    ReplyDelete
  69. Your session_register("myusername");
    $_SESSION['login_user']=$myusername;

    produces an error of session_register function is deprecated..

    can you post another example without this error

    thank you

    ReplyDelete
  70. great script it very essential for me.. i was searching too long time

    ReplyDelete
  71. for :

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\xampp\testingan\login.php on line 12

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\xampp\testingan\login.php on line 14

    you can change this :

    $sql="SELECT id FROM admin WHERE username='$username' and password='$password'";

    change admin to database phpmyadmin you table,so will work.

    ReplyDelete
  72. thnx for such a nice script
    its fully working on linux local machine
    but when i put it online then its not working ....
    help plz....

    ReplyDelete
  73. Useful post for php biggeners !

    ReplyDelete
  74. This is better than your previous Pagination tutorial with Jquery ajax.

    ReplyDelete
  75. when i logout, and press back button, it takes me back login again. . help me with that code. .

    ReplyDelete
  76. i have problem with adding quantity

    See this link

    http://lensbazaar.com/index.php?route=product/product&product_id=46

    ReplyDelete
  77. good nice .... very helpful...
    it could be done in singe php file...
    show example in single file.

    ReplyDelete
  78. I made a more professional version of this, you can get the script for free on php-login.net

    ReplyDelete
  79. can send me PM about this wrong?

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\testnew\login.php on line 16

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\testnew\login.php on line 19

    ReplyDelete
  80. thank you very very very much

    ReplyDelete
  81. what to do when our browser doesnot support SESSION and COOKIE both ???

    ReplyDelete
  82. give undefined index error

    ReplyDelete
  83. virar rocks ! ! !

    ReplyDelete
  84. when i click submit i am not redirected into the welcome.php page.

    ReplyDelete
  85. thank you very much......................

    ReplyDelete
  86. Thank it really works.... you're such a geek

    ReplyDelete
  87. every time i submit the form,the following error accure-Notice: Undefined index: email in C:\wamp\www\myserver\login.php on line 7

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\myserver\login.php on line 12

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\myserver\login.php on line 14

    ReplyDelete
  88. everytime i am entering the username or password,the following error accure...

    Undefined index: email in C:\wamp\www\myserver\login.php on line 7

    (I'm using email in the place of username in table.

    ReplyDelete
  89. On server its not running Session can not be expiring clicking on logout, while on local host its perfect running

    ReplyDelete
  90. On server its not running Session can not be expiring clicking on logout, while on local host its perfect running

    how to solve this, kindly help

    ReplyDelete
  91. Good nice Login form code

    ReplyDelete
  92. Hi all,
    I'm trying use this code on my server and my problem is: If I push 'Submit' button I'm looking at empty page. I think that redirection does not work. Can anyone help me?

    Thanks, Marty

    ReplyDelete
  93. thank you very much, please give us more advance samples, please, we love to study

    is there any samples to be edit Multiple User Accounts and User Logins.

    please!

    Regards,

    ReplyDelete
  94. can any one add Line of code for md5 in the same script i am converting my password in md5 format from backend but after doing this i am unable to log in . rest script is working without md 5

    ReplyDelete
  95. itss only working when user name is test

    ReplyDelete
  96. please let me know how it will work with other username now its not working with other id itss urgetn

    ReplyDelete
  97. i got my answer thnaks and its use full very

    ReplyDelete
  98. O O,

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/a4601813/public_html/New/Login.php on line 12
    Free Web Hosting

    PHP Error Message


    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/a4601813/public_html/New/Login.php on line 14

    ReplyDelete
  99. Hey.. bro.. I run your code it really runs fine.
    But, whenever i enter invalid password or username.. It doesn't gives me an error invalid username or password ? Really this helped me a lot..

    ReplyDelete
  100. thank you very much.

    ReplyDelete
  101. Very Useful blog. Thanks to srinivas for sharing his knowledge. I am newbie to php,struggling to learn. This site is helping me. Keep It Up

    ReplyDelete
  102. Please Let me know which editor is good for php beginners

    ReplyDelete
  103. thanks a lot.....
    am happy with this code....
    and am encrypted my password with base64_encode() function and its text field is "password"....
    i can learn the concept of session and also my login page is worked.... am too happy... thanks and thanks..

    ReplyDelete
  104. thanks a lot for awesome post.....

    it's work properly..........

    ReplyDelete
  105. Great help, thanks!

    ReplyDelete
  106. THis is very good code ,it is help me

    ReplyDelete
  107. session register function is DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. Then how to use it in php 5.3 or in latest version.
    Please provide solution for that

    ReplyDelete
  108. Thanks for this, helped me to understand sessions better.

    Anyone wanting to store the passwords in an MD5 can so so easily by firstly ensuring the passwords are MD5 in the database (store it in a VARCHAR) and then simply add $mypassword=md5($mypassword); under $mypassword=addslashes($_POST['password']);

    Easy

    ReplyDelete
  109. nice code
    thanks......................

    ReplyDelete
  110. Login script is not working properly when i tried to open login page with a modal box.

    ReplyDelete
  111. i need next and previous code in php data fetch from database mysql)

    ReplyDelete
  112. This is my php login code can help me if user forget there password or username...which part should it place

    = 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;

    if (isset($_SESSION['PrevUrl']) && false) {
    $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
    }
    header("Location: " . $MM_redirectLoginSuccess );
    }
    else {
    header("Location: ". $MM_redirectLoginFailed );
    }
    }
    ?>

    ReplyDelete
  113. Fatal error: Call to undefined function session_register() in C:\wamp\www\login\login.php on line 25

    ReplyDelete
  114. Just a quick note. session_register() is no longer used. Use session_start() instead.

    ReplyDelete
  115. Awesome.!! and nice..
    really useful and understable...

    ReplyDelete
  116. i creat a page with an identifiant and 2 radio button but when i write an exist identifiant the page login reload but when i write one that not existe a msg affiche that isn't exist ,,, i think that the probleme is here
    if($count==1)
    {
    session_register("ID_emp");
    $_SESSION['lofin_user']=$myID_emp;
    header("location: welcome.php");
    }
    else
    {
    print("votre Identifiant n'existe pas");
    }
    }

    ReplyDelete
  117. very helpful!
    thank u very muchhhhhhhh!

    ReplyDelete
  118. Hi buddy.... thank you very much.. Good luck !!! Keep up the good work

    ReplyDelete
  119. hii thanks its nice but i want login with jquery ajax can u help?

    ReplyDelete
  120. how to seprate with user login and admin login in this concept plz help.

    ReplyDelete
  121. how to seprate with user login and admin login in this concept plz help.

    ReplyDelete
  122. Thanks it help me out a lot

    ReplyDelete
  123. login_user is refered to what?? plz help

    ReplyDelete
  124. was really helpful for me and easy to understand too , Thank you

    ReplyDelete
  125. VERY VERY GOOD..THANKS!

    ReplyDelete
  126. Warning: session_start(): open(C:\php\sessiondata\\sess_fb64rb9kvfhtuamashcoip2i84, O_RDWR) failed: No such file or directory (2) in D:\htdocs\mater\project\login\login.php on line 4

    ReplyDelete
  127. Thank for this post

    ReplyDelete

  128. help i have such a problem

    SCREAM: Error suppression ignored for
    ( ! ) Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES) in C:\wamp\www\StudentInformationProject\conection.php on line 2


    my connection code are




    ReplyDelete
  129. in Login.php section you are starting with >?Php

    ReplyDelete
  130. Thanks for the script.

    But can you do an example on how to make a page to change password?

    ReplyDelete
  131. I make simple function to encrypt the password...
    hope this usefull

    ReplyDelete
  132. I am getting this error in login.php
    and also not redirecting on welcome page.
    please Help

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\login\login.php on line 16

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\login\login.php on line 19

    ReplyDelete
  133. It's Work nice but i have one dubt

    what is the use of $row['active'] in login.php

    ReplyDelete
  134. How to get session value in cron job page ?

    Plz answer this ........


    Thanks Avishek

    ReplyDelete
  135. why are you use session_register ....?????

    ReplyDelete
  136. wow!nice coding thank's for sharing

    ReplyDelete
  137. It's work fine i need login with multi users in redirect to different page

    ReplyDelete
  138. Very nice tutorial. This helped me a lot.. Thanks.

    ReplyDelete
  139. Notice: Undefined index: active in D:\www\login\login.php and
    Fatal error: Call to undefined function session_register() in D:\www\login\login.php .Plz help

    ReplyDelete

Make in India