PHP Login Page Example.
Wall Script
Wall Script
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");
}
?>
web notification

243 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. 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
  5. something is one word

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

    ReplyDelete
  7. 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
  8. Plain text pass-wording != good idea. Use MD5 (varchar[32]) or SHA1 (varchar[40])

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

    ReplyDelete
  10. THank You very much
    It really helped

    ReplyDelete
  11. 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
  12. nice work..thanks

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

    ReplyDelete
  14. great code, I love this one

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

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

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

    Ta!

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

    ReplyDelete
  19. very helpfulll...........great...

    ReplyDelete
  20. 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
  21. 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
  22. TNKS YOU VERY MUCH....!!!!!!!!!!!!!!!!!!!!!

    ReplyDelete
  23. 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
  24. @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
  25. 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
  26. 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
  27. there is an error on the first line of login.php - youve writetn >?php instead of <?php

    ReplyDelete
  28. 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
  29. Hello, i find some problems with your "Login.php"

    >?php

    it should be

    <?php

    ReplyDelete
  30. very good post
    its usefull form me
    Ashish

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

    ReplyDelete
  32. 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
  33. 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
  34. this code is very useful for all php programmers...

    ReplyDelete
  35. 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
  36. 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
  37. Really easy 4 unnderstand...thanx....

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

    ReplyDelete
  39. 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
  40. session_start();
    if(!isset($_SESSION['login_user'])){
    header("location:login.php");}

    thanks for the lock.php code

    from anonymous posted june 25 2011

    ReplyDelete
  41. nice code, it helps more

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

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

    ReplyDelete
  44. thankssssssssssssssssssss

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

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

    Thanks

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

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

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

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

    ReplyDelete
  51. 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
  52. thanks! and too much easy code..

    ReplyDelete
  53. 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
  54. Thanks ,,,,,,,,, really helped me out.

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

    in "welcome.php"

    $login_session; is undefined variable;

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

    ReplyDelete
  57. your not setting or retrieving the sesstions

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

    ReplyDelete
  59. Superb... Thanks Man...

    ReplyDelete
  60. Hello, Your script is awesome!

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


    thanks

    ReplyDelete
  61. 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
  62. nice code...........it is very very helpful to me

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

    --ATM

    ReplyDelete
  64. thanks,thanks,thanks :)

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

    ReplyDelete
  66. 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
  67. great script it very essential for me.. i was searching too long time

    ReplyDelete
  68. 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
  69. 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
  70. Useful post for php biggeners !

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

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

    ReplyDelete
  73. i have problem with adding quantity

    See this link

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

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

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

    ReplyDelete
  76. 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
  77. thank you very very very much

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

    ReplyDelete
  79. give undefined index error

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

    ReplyDelete
  81. thank you very much......................

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

    ReplyDelete
  83. 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
  84. 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
  85. On server its not running Session can not be expiring clicking on logout, while on local host its perfect running

    ReplyDelete
  86. 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
  87. Good nice Login form code

    ReplyDelete
  88. 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
  89. 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
  90. 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
  91. itss only working when user name is test

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

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

    ReplyDelete
  94. 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
  95. 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
  96. thank you very much.

    ReplyDelete
  97. 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
  98. Please Let me know which editor is good for php beginners

    ReplyDelete
  99. 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
  100. thanks a lot for awesome post.....

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

    ReplyDelete
  101. Great help, thanks!

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

    ReplyDelete
  103. 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
  104. 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
  105. nice code
    thanks......................

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

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

    ReplyDelete
  108. 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
  109. Fatal error: Call to undefined function session_register() in C:\wamp\www\login\login.php on line 25

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

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

    ReplyDelete
  112. 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
  113. very helpful!
    thank u very muchhhhhhhh!

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

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

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

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

    ReplyDelete
  118. Thanks it help me out a lot

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

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

    ReplyDelete
  121. VERY VERY GOOD..THANKS!

    ReplyDelete
  122. 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
  123. Thank for this post

    ReplyDelete

  124. 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
  125. in Login.php section you are starting with >?Php

    ReplyDelete
  126. Thanks for the script.

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

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

    ReplyDelete
  128. 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
  129. It's Work nice but i have one dubt

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

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

    Plz answer this ........


    Thanks Avishek

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

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

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

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

    ReplyDelete
  135. 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
  136. Hello ! And super great fror sharing this... I have a little problem.. I think I have installed everything correct, but when I launch the "main" page Login.php , I see only a message like "Opps some thing went wrong" What em I doing wrong!`

    Would be super duper happy to be able to solve the problem .. Thanks again !

    ReplyDelete
  137. very help full script for me............

    ReplyDelete

mailxengine Youtueb channel
Make in India
X