This post for PHP beginners Login Page Example. I want to explain creating database, posting form values, storing the session value and destroy the session. It's is very useful and simple. Try live demo with Username : test Password : test

Download Script
Live DemoDatabase
MySQL admin table columns id, username, passcode.
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE,
passcode VARCHAR(30)
);
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE,
passcode VARCHAR(30)
);
Config.php
Database configuration file.
<?php
$mysql_hostname = "hostname";$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
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=addslashes($_POST['username']); $mypassword=addslashes($_POST['password']);
$sql="SELECT id FROM admin WHERE username='$myusername' and passcode='$mypassword'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_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=mysql_query("select username from admin where username='$user_check' ");
$row=mysql_fetch_array($ses_sql);
$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");
}
?>









Very useful post.
Thanks
thanks :)
Bien!!!
Your session checking not very secure.
Thanks! Very helpful!
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.)
something is one word
As Anonymous said, it's not good practice to store user passwords in a database in cleartext.
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
Plain text pass-wording != good idea. Use MD5 (varchar[32]) or SHA1 (varchar[40])
Yes I agree. We need to encrypt the password.
THank You very much
It really helped
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
good! good!
nice work..thanks
nice work....very helpful for the beginners....
nice
great code, I love this one
super
Thanks Beib....
thanks.
Thanks man, for this post it was life saving ....
put more
perfect.
thanks.
wwoowwww.........
thanks budddyyy..........perfect
uuummmmaaaahhhhhhhhhh......on ur cheek :)
Nice little script Srinivas! The session part is nice & clean.
Ta!
nice and clean. thank you :)
Thanks
Thanks it's very useful .., please add the many sample examples.
very helpfulll...........great...
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
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??
TNKS YOU VERY MUCH....!!!!!!!!!!!!!!!!!!!!!
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??
@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)
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
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");
thanks
there is an error on the first line of login.php - youve writetn >?php instead of <?php
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...:)
thanks...
Hello, i find some problems with your "Login.php"
>?php
it should be
<?php
very good post
its usefull form me
Ashish
lock.php something wrong hah?
Confused -,-
thanks!!!
super
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
Its very useful
nice
nice and useful
tnx...
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
this code is very useful for all php programmers...
Thanx for the useful tip
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??
good
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
Thanks. Helpful!!!
Really easy 4 unnderstand...thanx....
good i can make use of this pieces of codes
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
session_start();
if(!isset($_SESSION['login_user'])){
header("location:login.php");}
thanks for the lock.php code
from anonymous posted june 25 2011
nice code, it helps more
22 yar sira code hai
......
awesmmm code 22 g......
i have one problem with this code, when i submit a login form page just reload and doesnt redirect to the header location.
thankssssssssssssssssssss
AM going to see if it is helpful. thx!
Thanks
Your tutorial was like a pain killer for my headache.
please post more articles.
Thanks
very useful for me as I am a beginner in PHP
great tutorial! helped me make my first steps in a new language.
great, thanks
Nice... Thanks...
man u da master.
thanks nice post.
can u please provide the same code for users login.
thanks in advance
thanks nice post.
nice post and thanks.its very useful for the students those who are doing live project.thanq sir......
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
Thx Dude! Great post!
thanks
thanks! and too much easy code..
nice post
Thanks!
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
Thanks ,,,,,,,,, really helped me out.
it was a nice post ....
but i m getting a error
in "welcome.php"
$login_session; is undefined variable;
thanks man
Thanks...this will be helpful for beginners.
thanks for help
your not setting or retrieving the sesstions
great
It's very nice post,and specially it's good for beginners...
thanks a lot...
Superb... Thanks Man...
Hello, Your script is awesome!
Can you tell me how to session time out automatically if page is idle.
thanks
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
Nice....
nice code...........it is very very helpful to me
You are simply superb, expecting more useful articles from you
--ATM
thanks,thanks,thanks :)
good tutorial for newbies
am a newbie..thnx ..ths isht's clear n precise
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
great script it very essential for me.. i was searching too long time
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.
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....
clean and simple :)
Useful post for php biggeners !
This is better than your previous Pagination tutorial with Jquery ajax.
when i logout, and press back button, it takes me back login again. . help me with that code. .
thanx
Thanks
i have problem with adding quantity
See this link
http://lensbazaar.com/index.php?route=product/product&product_id=46
gr8 tuto....
good nice .... very helpful...
it could be done in singe php file...
show example in single file.
Nice Code
I made a more professional version of this, you can get the script for free on php-login.net
its good example..
thanks
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
thank you very very very much
nice code...
what to do when our browser doesnot support SESSION and COOKIE both ???
Thank you so so much...
give undefined index error
nice 1.. loved it
virar rocks ! ! !
This is really important.
when i click submit i am not redirected into the welcome.php page.
good
thank you very much......................
Thank it really works.... you're such a geek
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
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.
On server its not running Session can not be expiring clicking on logout, while on local host its perfect running
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
Thanks
Thanks
Good nice Login form code
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
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,
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
itss only working when user name is test
please let me know how it will work with other username now its not working with other id itss urgetn
i got my answer thnaks and its use full very
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
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..
thank you very much.
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
Please Let me know which editor is good for php beginners
veryy very thabksssssssssssss
thanx alot!
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..
very Helpful
thanks a lot for awesome post.....
it's work properly..........
very Helpful
Great help, thanks!
THis is very good code ,it is help me
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
very use full ...........
thanks.........
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
nice code
thanks......................
Login script is not working properly when i tried to open login page with a modal box.
GREAT JOB
Awesome..!!
i need next and previous code in php data fetch from database mysql)
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 );
}
}
?>
Fatal error: Call to undefined function session_register() in C:\wamp\www\login\login.php on line 25
Thanks ^__^ I learned A lot!!!
thanks a lot !
Thanks.
Just a quick note. session_register() is no longer used. Use session_start() instead.
Awesome.!! and nice..
really useful and understable...
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");
}
}
very helpful!
thank u very muchhhhhhhh!
Hi buddy.... thank you very much.. Good luck !!! Keep up the good work
thanx
hii thanks its nice but i want login with jquery ajax can u help?
how to seprate with user login and admin login in this concept plz help.
how to seprate with user login and admin login in this concept plz help.
Thnx for this post