9lessons programming blog
Loading Search
9lessons Bring Friends
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

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



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);
?>

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']);

$sql="SELECT id FROM admin WHERE username='$myusername' and passcode='$mypassword'";
$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");
}
?>
Comments
{ 227 comments }
Anonymous said...

Very useful post.
Thanks

Anonymous said...

thanks :)

Anonymous said...

Bien!!!

JasonDavis said...
This comment has been removed by the author.
Anonymous said...

Your session checking not very secure.

Dave said...

Thanks! Very helpful!

Anonymous said...

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

Anonymous said...

something is one word

rwenderlich said...

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

2010 ELECTION said...

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

Anonymous said...

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

Srinivas Tamada said...

Yes I agree. We need to encrypt the password.

Anonymous said...

THank You very much
It really helped

George said...

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

Anonymous said...

good! good!

Anonymous said...

nice work..thanks

Anonymous said...

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

Anonymous said...

nice

Anonymous said...

great code, I love this one

Anonymous said...

super

Anonymous said...

Thanks Beib....

Anonymous said...

thanks.

Anonymous said...

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

Anonymous said...

perfect.

thanks.

Anonymous said...

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

Anonymous said...

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

Ta!

ak0cmimi said...

nice and clean. thank you :)

Anonymous said...

Thanks

Anonymous said...

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

Anonymous said...

very helpfulll...........great...

Anonymous said...

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

Anonymous said...

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??

Anonymous said...

TNKS YOU VERY MUCH....!!!!!!!!!!!!!!!!!!!!!

yu said...

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??

Anonymous said...

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

Anonymous said...

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

Anonymous said...

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");

Anonymous said...

thanks

Anonymous said...

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

JOMI N.J said...

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

Anonymous said...

thanks...

Drei said...

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

>?php

it should be

<?php

Anonymous said...

very good post
its usefull form me
Ashish

Sembunyi said...

lock.php something wrong hah?
Confused -,-

Anonymous said...

thanks!!!

chandhru cool said...

super

Satyanarayan said...

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

piraimathi said...

Its very useful

Anonymous said...

nice

Anonymous said...

nice and useful

Anonymous said...

tnx...

Anonymous said...

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

Abhimanyu Malhotra said...

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

priyabrata said...

Thanx for the useful tip

Anonymous said...

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??

Anonymous said...

good

Anonymous said...

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

Anonymous said...

Thanks. Helpful!!!

Anonymous said...

Really easy 4 unnderstand...thanx....

deepak said...

good i can make use of this pieces of codes

Anonymous said...

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

ronald said...

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

thanks for the lock.php code

from anonymous posted june 25 2011

Anonymous said...

nice code, it helps more

Anonymous said...

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

Anonymous said...

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

Anonymous said...

thankssssssssssssssssssss

Anonymous said...

AM going to see if it is helpful. thx!

Anonymous said...

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

Thanks

Anonymous said...

very useful for me as I am a beginner in PHP

Anonymous said...

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

asdf said...

great, thanks

Anonymous said...

Nice... Thanks...

Anonymous said...

man u da master.

ahmed said...

thanks nice post.

ahmed said...

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

ahmed said...

thanks nice post.

Rajesh said...

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

Anonymous said...

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

Ferlezcano said...

Thx Dude! Great post!

archana said...

thanks

archana said...

thanks! and too much easy code..

Anonymous said...

nice post

aaaaaaa said...

Thanks!

Anonymous said...

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

Varun Kalodia said...

Thanks ,,,,,,,,, really helped me out.

suchait said...

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

in "welcome.php"

$login_session; is undefined variable;

Anonymous said...

thanks man

Raj said...

Thanks...this will be helpful for beginners.

Anonymous said...

thanks for help

Anonymous said...

your not setting or retrieving the sesstions

Anonymous said...

great

Abebe said...

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

Anonymous said...

Superb... Thanks Man...

Chirag Shah said...

Hello, Your script is awesome!

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


thanks

Anonymous said...

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

VT said...

Nice....

Anonymous said...

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

Anonymous said...

You are simply superb, expecting more useful articles from you

--ATM

sh said...

thanks,thanks,thanks :)

Shujaat Ali said...

good tutorial for newbies

Anonymous said...

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

Anonymous said...

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

Ravind said...

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

don po said...

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.

suchait said...

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

Malshan Gunawardane said...

clean and simple :)

Anonymous said...

Useful post for php biggeners !

Jagan Krishnaraj said...

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

Anonymous said...

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

webengineersrilanka said...

thanx

Anonymous said...

Thanks

lens bazaar said...

i have problem with adding quantity

See this link

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

lens bazaar said...

gr8 tuto....

venkat raman said...

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

Anonymous said...

Nice Code

Chris said...

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

Shabbir said...

its good example..
thanks

Hatta Yuthafiga said...

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

Pratap said...

thank you very very very much

Anonymous said...

nice code...

Abhishek Rawat said...

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

Madhawa said...

Thank you so so much...

Anonymous said...

give undefined index error

SuRaJ pAwAr said...

nice 1.. loved it

Anonymous said...

virar rocks ! ! !

Edau Joel said...

This is really important.

Flint said...

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

Anonymous said...

good

Anonymous said...

thank you very much......................

Raymond Nuñez said...

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

chandra shekhar gupta said...

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

chandra shekhar gupta said...

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.

vishal said...

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

Anil said...

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

KedarLasane said...

Thanks

Anonymous said...

Thanks

Anonymous said...

Good nice Login form code

Anonymous said...

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

reshan said...

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,

Dev Chauhan said...

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

Anonymous said...

itss only working when user name is test

Anonymous said...

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

Anonymous said...

i got my answer thnaks and its use full very

Anonymous said...

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

Anonymous said...

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

Anonymous said...

thank you very much.

Anonymous said...

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

Anonymous said...

Please Let me know which editor is good for php beginners

non veg said...

veryy very thabksssssssssssss

royal said...

thanx alot!

benila anoop said...

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

Anonymous said...

very Helpful

sahban ali said...

thanks a lot for awesome post.....

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

Anonymous said...

very Helpful

Anonymous said...

Great help, thanks!

mangal kachhawa said...

THis is very good code ,it is help me

Girish Rane said...

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

Deepak Maurya said...

very use full ...........

Deepak Maurya said...

thanks.........

Wookie said...

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

Jignesh Viradiya said...

nice code
thanks......................

Anonymous said...

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

Anonymous said...

GREAT JOB

Anonymous said...

Awesome..!!

Snehasis Das said...

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

Emi Muizz said...

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 );
}
}
?>

Anonymous said...

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

Almondyseth Sato said...

Thanks ^__^ I learned A lot!!!

Peerasak said...

thanks a lot !

khyati said...

Thanks.

Anonymous said...

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

Anonymous said...

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

saoudi alaeddine said...

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");
}
}

Anonymous said...

very helpful!
thank u very muchhhhhhhh!

Anonymous said...

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

Anonymous said...

thanx

Anonymous said...

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

vijai said...

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

Anonymous said...

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

Praveen V R said...

Thnx for this post

Anonymous said...

Thanks it help me out a lot

Anonymous said...

login_user is refered to what?? plz help

jigitsa rathod said...

thanx...

Anonymous said...

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

Anonymous said...

VERY VERY GOOD..THANKS!

Anonymous said...

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

Anonymous said...

Thank for this post

Sombi Willingtone said...


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




Anonymous said...

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

Anonymous said...

Thanks for the script.

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

Husni said...

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

Anonymous said...

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

vijai said...

It's Work nice but i have one dubt

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

Avishek Koley said...

How to get session value in cron job page ?

Plz answer this ........


Thanks Avishek

pusber said...

Thank for this post

Sagar Patel said...

why are you use session_register ....?????

venkat said...

wow!nice coding thank's for sharing

vijai said...

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

Anonymous said...

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

soth vandy said...

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

Post a Comment