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.
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)
);
(
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);
?>
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");
}
?>
Very useful post.
ReplyDeleteThanks
thanks :)
ReplyDeleteBien!!!
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteYour session checking not very secure.
ReplyDeleteThanks! Very helpful!
ReplyDeleteA few hints:
ReplyDelete– 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
ReplyDeleteAs Anonymous said, it's not good practice to store user passwords in a database in cleartext.
ReplyDeletego to this site they have a tutorial on how to creat a simple login registration php
ReplyDeletehttp://dudes-online.zxq.net/viewtopic.php?f=2&t=2
Plain text pass-wording != good idea. Use MD5 (varchar[32]) or SHA1 (varchar[40])
ReplyDeleteYes I agree. We need to encrypt the password.
ReplyDeleteTHank You very much
ReplyDeleteIt 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']):
ReplyDeletegogto login page
good! good!
ReplyDeletenice work..thanks
ReplyDeletenice work....very helpful for the beginners....
ReplyDeletenice
ReplyDeletegreat code, I love this one
ReplyDeletesuper
ReplyDeleteThanks Beib....
ReplyDeletethanks.
ReplyDeleteThanks man, for this post it was life saving ....
ReplyDeleteput more
perfect.
ReplyDeletethanks.
wwoowwww.........
ReplyDeletethanks budddyyy..........perfect
uuummmmaaaahhhhhhhhhh......on ur cheek :)
Nice little script Srinivas! The session part is nice & clean.
ReplyDeleteTa!
nice and clean. thank you :)
ReplyDeleteThanks
ReplyDeleteThanks it's very useful .., please add the many sample examples.
ReplyDeletevery helpfulll...........great...
ReplyDeletei have tried your entire script
ReplyDeletebut 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
ReplyDeleteOpps some thing went wrong
guys can you please help me with this erroe??
TNKS YOU VERY MUCH....!!!!!!!!!!!!!!!!!!!!!
ReplyDeleteWarning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'@'localhost' (using password: YES) in C:\xampp\htdocs\login\config.php on line 7
ReplyDeleteOpps 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)
ReplyDelete1. don't store passwords, use an md5 hash or better
ReplyDelete2. 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.
ReplyDelete1) 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");
there is an error on the first line of login.php - youve writetn >?php instead of <?php
ReplyDeletethanks for the sample login program...
ReplyDeleteit helped to anlyze where i went wrong..
thanks again.. im adding your site to ma favourite list.. keep up the good work buddy...:)
thanks...
ReplyDeleteHello, i find some problems with your "Login.php"
ReplyDelete>?php
it should be
<?php
very good post
ReplyDeleteits usefull form me
Ashish
lock.php something wrong hah?
ReplyDeleteConfused -,-
thanks!!!
ReplyDeletesuper
ReplyDeleteWhat is this yaar ?
ReplyDeleteDis 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
ReplyDeletenice and useful
ReplyDeletetnx...
ReplyDeleteDoesnt work!!
ReplyDeleteErrors 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...
ReplyDeleteThanx for the useful tip
ReplyDeleteI am a little confused on the if ($count) statement
ReplyDeleteyou 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??
Notice: Undefined index: active in C:\wamp\www\login.php on line 17
ReplyDeleteFatal error: Call to undefined function session_register() in C:\wamp\www\login.php on line 25
kidly solve
Thanks. Helpful!!!
ReplyDeleteReally easy 4 unnderstand...thanx....
ReplyDeletegood i can make use of this pieces of codes
ReplyDeleteI write bad angel, but hope you understand.
ReplyDeleteThis 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();
ReplyDeleteif(!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
ReplyDelete22 yar sira code hai
ReplyDelete......
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.
ReplyDeletethankssssssssssssssssssss
ReplyDeleteAM going to see if it is helpful. thx!
ReplyDeleteThanks
ReplyDeleteYour 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
ReplyDeletegreat tutorial! helped me make my first steps in a new language.
ReplyDeletegreat, thanks
ReplyDeleteNice... Thanks...
ReplyDeleteman u da master.
ReplyDeletethanks nice post.
ReplyDeletecan u please provide the same code for users login.
ReplyDeletethanks in advance
thanks nice post.
ReplyDeletenice post and thanks.its very useful for the students those who are doing live project.thanq sir......
ReplyDeletehi,
ReplyDeletethanks 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!
ReplyDeletethanks
ReplyDeletethanks! and too much easy code..
ReplyDeletenice post
ReplyDeleteThanks!
ReplyDeleteWarning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\xampp\testingan\login.php on line 12
ReplyDeleteWarning: 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.
ReplyDeleteit was a nice post ....
ReplyDeletebut i m getting a error
in "welcome.php"
$login_session; is undefined variable;
thanks man
ReplyDeleteThanks...this will be helpful for beginners.
ReplyDeletethanks for help
ReplyDeleteyour not setting or retrieving the sesstions
ReplyDeletegreat
ReplyDeleteIt's very nice post,and specially it's good for beginners...
ReplyDeletethanks a lot...
Superb... Thanks Man...
ReplyDeleteHello, Your script is awesome!
ReplyDeleteCan you tell me how to session time out automatically if page is idle.
thanks
i have error came out..
ReplyDeleteWarning: 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....
ReplyDeletenice code...........it is very very helpful to me
ReplyDeleteYou are simply superb, expecting more useful articles from you
ReplyDelete--ATM
thanks,thanks,thanks :)
ReplyDeletegood tutorial for newbies
ReplyDeleteam a newbie..thnx ..ths isht's clear n precise
ReplyDeleteYour session_register("myusername");
ReplyDelete$_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
ReplyDeletefor :
ReplyDeleteWarning: 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
ReplyDeleteits fully working on linux local machine
but when i put it online then its not working ....
help plz....
clean and simple :)
ReplyDeleteUseful post for php biggeners !
ReplyDeleteThis is better than your previous Pagination tutorial with Jquery ajax.
ReplyDeletewhen i logout, and press back button, it takes me back login again. . help me with that code. .
ReplyDeletethanx
ReplyDeleteThanks
ReplyDeletei have problem with adding quantity
ReplyDeleteSee this link
http://lensbazaar.com/index.php?route=product/product&product_id=46
gr8 tuto....
ReplyDeletegood nice .... very helpful...
ReplyDeleteit could be done in singe php file...
show example in single file.
Nice Code
ReplyDeleteI made a more professional version of this, you can get the script for free on php-login.net
ReplyDeleteits good example..
ReplyDeletethanks
can send me PM about this wrong?
ReplyDeleteWarning: 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
ReplyDeletenice code...
ReplyDeletewhat to do when our browser doesnot support SESSION and COOKIE both ???
ReplyDeleteThank you so so much...
ReplyDeletegive undefined index error
ReplyDeletenice 1.. loved it
ReplyDeletevirar rocks ! ! !
ReplyDeleteThis is really important.
ReplyDeletewhen i click submit i am not redirected into the welcome.php page.
ReplyDeletegood
ReplyDeletethank you very much......................
ReplyDeleteThank it really works.... you're such a geek
ReplyDeleteevery time i submit the form,the following error accure-Notice: Undefined index: email in C:\wamp\www\myserver\login.php on line 7
ReplyDeleteWarning: 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...
ReplyDeleteUndefined 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
ReplyDeleteOn server its not running Session can not be expiring clicking on logout, while on local host its perfect running
ReplyDeletehow to solve this, kindly help
Thanks
ReplyDeleteThanks
ReplyDeleteGood nice Login form code
ReplyDeleteHi all,
ReplyDeleteI'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
ReplyDeleteis 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
ReplyDeleteitss only working when user name is test
ReplyDeleteplease let me know how it will work with other username now its not working with other id itss urgetn
ReplyDeletei got my answer thnaks and its use full very
ReplyDeleteO O,
ReplyDeleteWarning: 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.
ReplyDeleteBut, 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.
ReplyDeleteVery 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
ReplyDeletePlease Let me know which editor is good for php beginners
ReplyDeleteveryy very thabksssssssssssss
ReplyDeletethanx alot!
ReplyDeletethanks a lot.....
ReplyDeleteam 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
ReplyDeletethanks a lot for awesome post.....
ReplyDeleteit's work properly..........
very Helpful
ReplyDeleteGreat help, thanks!
ReplyDeleteTHis is very good code ,it is help me
ReplyDeletesession 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.
ReplyDeletePlease provide solution for that
very use full ...........
ReplyDeletethanks.........
ReplyDeleteThanks for this, helped me to understand sessions better.
ReplyDeleteAnyone 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
ReplyDeletethanks......................
Login script is not working properly when i tried to open login page with a modal box.
ReplyDeleteGREAT JOB
ReplyDeleteAwesome..!!
ReplyDeletei need next and previous code in php data fetch from database mysql)
ReplyDeleteThis is my php login code can help me if user forget there password or username...which part should it place
ReplyDelete= 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
ReplyDeleteThanks ^__^ I learned A lot!!!
ReplyDeletethanks a lot !
ReplyDeleteThanks.
ReplyDeleteJust a quick note. session_register() is no longer used. Use session_start() instead.
ReplyDeleteAwesome.!! and nice..
ReplyDeletereally 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
ReplyDeleteif($count==1)
{
session_register("ID_emp");
$_SESSION['lofin_user']=$myID_emp;
header("location: welcome.php");
}
else
{
print("votre Identifiant n'existe pas");
}
}
very helpful!
ReplyDeletethank u very muchhhhhhhh!
Hi buddy.... thank you very much.. Good luck !!! Keep up the good work
ReplyDeletethanx
ReplyDeletehii thanks its nice but i want login with jquery ajax can u help?
ReplyDeletehow to seprate with user login and admin login in this concept plz help.
ReplyDeletehow to seprate with user login and admin login in this concept plz help.
ReplyDeleteThnx for this post
ReplyDeleteThanks it help me out a lot
ReplyDeletelogin_user is refered to what?? plz help
ReplyDeletethanx...
ReplyDeletewas really helpful for me and easy to understand too , Thank you
ReplyDeleteVERY VERY GOOD..THANKS!
ReplyDeleteWarning: 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
ReplyDeleteThank for this post
ReplyDelete
ReplyDeletehelp 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
in Login.php section you are starting with >?Php
ReplyDeleteThanks for the script.
ReplyDeleteBut can you do an example on how to make a page to change password?
I make simple function to encrypt the password...
ReplyDeletehope this usefull
I am getting this error in login.php
ReplyDeleteand 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
It's Work nice but i have one dubt
ReplyDeletewhat is the use of $row['active'] in login.php
How to get session value in cron job page ?
ReplyDeletePlz answer this ........
Thanks Avishek
Thank for this post
ReplyDeletewhy are you use session_register ....?????
ReplyDeletewow!nice coding thank's for sharing
ReplyDeleteIt's work fine i need login with multi users in redirect to different page
ReplyDeleteVery nice tutorial. This helped me a lot.. Thanks.
ReplyDeleteNotice: Undefined index: active in D:\www\login\login.php and
ReplyDeleteFatal error: Call to undefined function session_register() in D:\www\login\login.php .Plz help
niceeeee!!!!!!
ReplyDeleteHello ! 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!`
ReplyDeleteWould be super duper happy to be able to solve the problem .. Thanks again !
very help full script for me............
ReplyDelete