PHP Login Script Tutorial
Please subscribe to ProTycoon.com via the RSS Feed or Via Email.
I have been asked to create a short tutorial to demonstrate how to make a simple PHP Login Script. I have put together 5 simple steps to help you get your PHP login script up and running in minutes.
Step 1: Create Members Table In Database
Before you can set up the Login Script you need to have the members table set up in your MySql database. Below is the code to create your members table:
CREATE TABLE `members` ( `id` int(4) NOT NULL auto_increment, `username` varchar(65) NOT NULL default '', `password` varchar(65) NOT NULL default '', PRIMARY KEY (`id`) ) TYPE=MyISAM AUTO_INCREMENT=2 ;
You then need to create a user that can be used to test the login script. This can be done using the code below:
INSERT INTO `members` VALUES (1, 'david', 'password');
Step 2: Create a Login Form
You now need to create a login form, where users can enter their username and password. Below is the code for a login form and submit button:
<form method="post" action="login.php"> <br />Username: <input type="text" id="username" name="username"> <br />Password: <input type="password" id="password" name="password"> <br /><input type="submit" name="Login" value="Login"> </form>
When the submit button is pressed it sends the information and the user to the ‘login.php’ page.
Step 3: Create the ‘login.php’ file
Below is the code for your ‘login.php’ file. You will need to enter your database information into the top part. It will then connect to your database, search for a match on the username and password entered in the form, if it finds a record the user is sent to the ‘login_success.php’ file, if not then an error message is displayed.
<?php $host="localhost"; // Host name
$dbusername=""; // Mysql username
$dbpassword=""; // Mysql password
$db_name=""; // Database name
$tbl="members"; // Table name
// This connects to server and then selects the members databse.
mysql_connect("$host", "$dbusername", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Assign the username and password from the form to variables.
$username=$_POST['username'];
$password=$_POST['password'];
$sql="SELECT * FROM $tbl WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// This counts to see how many rows were found, there should be no more than 1
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1
if($count==1){
// Register $myusername, and redirect to file "login_success.php"
session_start();
$_SESSION["logged"] = 1;
header("location:index.php");
}
else {
$_SESSION["logged"] = 0;
header("location:login.php");
}
?>
If the username and password is matched a ‘Session’ is started, for more information about ‘Sessions’, see our guide to sessions. You can send the user to any web page after then have logged in, you simply edit the location to the file you wish to send the user to. You will need to use the code from the top of the ‘login_success.php’ file to ensure that the user is logged in. If you are sending the user to the ‘login_success.php file you will need to create it now.
Step 4: Create the login_success.php file
If the username and password is matched in the ‘Login.php’ file then the user is sent to the ‘login_success.php’ file. This file needs to check that the user is logged in. If the user is logged in then they can see the page, if they are not logged in they are sent to the ‘notloggedin.php’ file. Below is the code that needs to be entered at the very top of the page.
// Check to see if session is not registered, if it is not redirect the user back to the notloggedin.php file.
// Put this code in first line of every web page that you only want logged-in users to see.
<?php session_start();
if($_SESSION['logged'] != 1){ header("location:login.php"); }
?>
You then continue with the rest of the web page as you normally would, for example:
<html> <body> Login Successful </body> </html>
Once your users are logged in you will need to give them the option to log-out.
Step 5: Create the logout.php file
When the user logged in you created a session, so to log the user out you need to remove the session. To do this you need to put the following code in the top line of your ‘logout.php file’:
<? session_start(); session_destroy(); ?>
This destroys the session. You can then continue with the webpage, and you could simply display a message to tell the user they have been logged out. You now have a working PHP login script, feel free to use it on your web site. Why not learn how to encrypt your PHP Login Script? If you have any problems please feel free to comment on this post and I will try to answer them as quickly as possible.













Encrypting Passwords in PHP Login Script | ProTycoon | February 20th, 2008 at 8:52 pm #
[...] tutorial is a follow up to our PHP Login Script Tutorial. You will learn how to encrypt passwords to make your login script more [...]
Seamus cooley | April 21st, 2008 at 1:44 pm #
Hi there,
You mention the file below but you havent showed it anywhere within your example so one just gets redirected to a page where it says that it is not found?
notloggedin.php
David Shaw | April 21st, 2008 at 2:09 pm #
Hi Seamus.
You will need to create a page that is called:
notloggedin.php
on this page you can simply say something like:
“This page is for memebers only. To become a member sign up here”………… etc
It is up to you what you want on that page, I am sorry that I did not make it very clear, will edit the tutorial to make this more clear.
Many Thanks for the feedback.
David
jens | April 22nd, 2008 at 5:52 pm #
hej,
without logging you can get access to eht login_success file
is this normal ???
David Shaw | April 23rd, 2008 at 3:13 pm #
@Jens
It sounds like you have made an error somewhere along the line.
Do you have this code at the top of your page:
< ?
session_start();
if(!session_is_registered(myusername)){
header("location:notloggedin.php");
}
?>
This checks to see if the user is logged in, then redirects them if they are not?
David
PHP Session Tutorial | ProTycoon | April 30th, 2008 at 7:30 am #
[...] A PHP session allows you to store information on the server for use on later pages, for example a username or shopping cart items. They can also be used in our PHP Login Script Tutorial. [...]
thomas | May 4th, 2008 at 11:01 pm #
I think there is a little mistake in the tutorial, because it says:
if(!session_is_registered(MYusername)){
instead of:
if(!session_is_registered(username)){
David Shaw | May 5th, 2008 at 8:16 am #
Cheers Thomas,
Had not noticed that. Will change it now!
Related Post Plugin Can Boost Page Views | ProTycoon | May 12th, 2008 at 11:02 am #
[...] most viewed post is currently my PHP Login Script Tutorial, this is also the page that gets landed on the most from search engines, at the bottom of the post [...]
Increase Page Views On Your Blog | ProTycoon | May 13th, 2008 at 9:03 am #
[...] a look at my Encrypting Passwords in PHP Login Script post you will notice that I have linked to my PHP Login Script Tutorial inside the post, this helps my visitor find related [...]
glenn | June 3rd, 2008 at 9:44 am #
Hi David nice tutorial, but I was wondering when I have loged in and aceesed the mebers area, how can I add in the users name ie.
welcome back: (The users name here)
I have been trying to find some tutorials for this
I have used the following code
// Display Member information
echo “Welcome back: ” . $_SESSION["SESS_MEMBER_ID"];
But the result I get is the tow number of the information I have changed MEMBER_ID to USERNAME but then I dont have any information shown.
Hope you can offer some advice
David Shaw | June 3rd, 2008 at 12:28 pm #
If you have registered the session called ‘username’ you can use this code:
echo “Welcome ” . $_SESSION['username'] . “”;
Let me know how you get on!
glenn | June 3rd, 2008 at 1:02 pm #
If I have registered the session….. that could be the problem I think the session is registered as member_id and then that is picking up the number 1, because if I change for example the ['Username'] then it only says Welcome and then ther eis nothing
I am new to PHP and have only just gone through a tutorial and then decided to add this bit on, do you suggest that I change the registed session if so how will that effect the rest of the code.
Any further help will be much appreachiated
David Shaw | June 3rd, 2008 at 1:45 pm #
Can you not just register another session variable called username?
glenn | June 3rd, 2008 at 2:18 pm #
I must sound like a real novice here David but I dont know how to I have only been working on this tutorial for 3 days and it is the first bit of php I have done.
how would i register another session where would that info go in the page
login-form.php
login-exec.php
and my gallery.php
( i am a photographer by profession but have been wanting to put some images online
I do appreachiate your help your giving me
glenn | June 3rd, 2008 at 2:37 pm #
I did reply to this but for some reason it is not showing up.
basicly David I have been looking at php for the past 3 days so a total novice
I dont knwo how to register another session called username how would I do it and where in my script would i put it.
I have three main pages
the memebers area gallery.php
the long in page
loginin-form.php
and the main code page section for the login scripts
login-exec.php
David Shaw | June 3rd, 2008 at 2:56 pm #
Have you seen my Session tutorial?
http://www.protycoon.com/index.php/2008/02/14/php-session-tutorial/
This shows some examples of how sessions work. You want to get the username they input and save it to the username session variable, then call it like I showed in my previous comment.
P.s What is your site?
glenn | June 3rd, 2008 at 3:36 pm #
I will give that a go, I am a photographer and I am just putting together a web site to show off some of my images but I dont want the whole world to see I want to know who is looking
i have to go now but i hope to try that out tomorrow and see how I get on.
thanks for your help and if I get stuck I hope you dont mind more questions
David Shaw | June 3rd, 2008 at 10:37 pm #
I welcome any questions you may have
glenn | June 4th, 2008 at 8:23 am #
David you will regret saying you welcome the questions
is there an email maybe I can email you my code because this is just not working
I have put the code in from your tutorial
this all works but the david part I want it to come from the log in so it is the usersname and I just dont know how to do this very frustrating i might of jumped in at the deepend here but this is all part of the lerning curve I guess
David Shaw | June 4th, 2008 at 3:57 pm #
Yeah sure.
You can contact me at this address:
adzeds(at)googlemail(dot)com
Hopefully can help.
glenn | June 5th, 2008 at 10:58 am #
I have sent you the file David, fingers crossed you can offer me some help
newbie | June 5th, 2008 at 3:20 pm #
Hello nice Tut.
But i have a problem,
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at login.php:11) in login.php on line 47
and another failure
Warning: Cannot modify header information - headers already sent by (output started at login.php:11) in login.php on line 53
newbie
what can i do?
thx
davin maslin | June 5th, 2008 at 3:29 pm #
I am having some trouble with your login script
i had added my database and evrything seemed to be working
well
but when a user clicks on login it always returns
a that i have the wrong username or password.
This cant be right as i wrote the user into the database
and definately know the password.
I have just copyed and pasted the script from the tutorial page to the relevant pages and edited nothing but the bits that relate to mysql server.
Could you plase help figure out why this isnt working
Thanks
newbie | June 6th, 2008 at 6:35 am #
its working … thx
David Shaw | June 6th, 2008 at 6:48 am #
Glad you have it working!
newbie | June 6th, 2008 at 10:50 am #
other problem
with the decryption site:
the login.php
<?php
$host=”localhost”;
$dbusername=”USERNAME”;
$dbpassword=”PASSWORD”;
$db_name=”login”;
$tbl=”members”;
mysql_connect(”$host”, “$dbusername”, “$dbpassword”)or die(”cannot connect”);
mysql_select_db(”$db_name”)or die(”cannot select Database”);
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$encrypted_password=md5($password);
$sql=”SELECT * FROM $tbl WHERE username=’.$username.’ and password=’.$encrypted_password.’”;
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
session_start();
session_register(”username”);
session_register(”encrypted_password”);
header(”location:login_success.php”);
}
echo <<<EOF
Username:
Password:
EOF;
?>
you can enter the username and the password … but i dont come to the site login_success.php.
without decrypet password it is working great.
in the database the password is encrypted.
do u have any idea why it does work?
David Shaw | June 6th, 2008 at 1:19 pm #
It looks ok to me.
I will keep looking at this and get back to you.!
glenn | June 6th, 2008 at 2:08 pm #
David did you manage to have a quick look through my code I sent you?
newbie | June 6th, 2008 at 5:08 pm #
david,yes i have made it like the tutorial, but it looks to me that the session doesnt start to the next page …

Jack | June 21st, 2008 at 6:24 pm #
session register is outdated.
Jamie | June 27th, 2008 at 8:18 am #
hey. iv followed the instructions step by step and it dosnt work?!?!!?! :S please somebody help iv been trying to do this for agers
guess its not going to happen help me. jacksonjamie@hotmail.co.uk
David Shaw | June 30th, 2008 at 10:13 am #
This page has been edited, it should work now!
David Shaw | June 30th, 2008 at 10:14 am #
Been fixed
David Shaw | June 30th, 2008 at 10:14 am #
Should be fixed now! Give it a try.
CharlieG | July 12th, 2008 at 6:52 pm #
Hi I followed your instructions, but everytime I login, I get the cannot connect thing!
COuld you send an email to charliebobgordon@hotmail.com and help me please thanks.
Kirk Richards | July 13th, 2008 at 9:34 pm #
I have the same problem as newbie. How do you resolve this:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/jkirkric/public_html/checklogin.php:3) in /home/jkirkric/public_html/checklogin.php on line 35
Warning: Cannot modify header information - headers already sent by (output started at /home/jkirkric/public_html/checklogin.php:3) in /home/jkirkric/public_html/checklogin.php on line 37
????
Many thanks!
Don | July 22nd, 2008 at 12:19 am #
David,
I am new to PHP. I want to direct each user to a different page based on what is in the database for that user.
IE. User 1 to /user1page.php
IE..User2 to /user2page.php
How would I do this?
newbie | July 24th, 2008 at 12:45 pm #
hello david
i works fine now, i tried it with encryptet password and https.
great work really
thx newbie
newbie | July 24th, 2008 at 12:48 pm #
@kirk
look if u have anything before <?php
look in the internet for this failure… its a simple problem
Jack | September 2nd, 2008 at 12:05 pm #
What i get is a redirect loop… any suggestions?
Adam | September 21st, 2008 at 3:39 pm #
Hi,
Im still ahving problems. There is no HTML behind ‘<?’, but I’m still getting errors like this;
‘Warning: Cannot modify header information - headers already sent by (output started at /home/wowdream/public_html/login.php:2)’
My pages are below:
Index.html:
Username:
Password:
Login.php:
Login_success.php :
Login Successful
If you could see anything thats wrong, please reply.
Kamin Miller | October 16th, 2008 at 10:02 pm #
Hopefully this is a simple question I cannot get a clear answer on. Are PHP sessions passed in the HTML headers like cookies? If I have a user browse the site for a few pages without using any of the stored session data, will it get lost? Will the session get lost when a user browses from a session enabled PHP page to an HTML page and back?
-Kamin
peter | November 3rd, 2008 at 5:46 am #
hi,
after login then go to other page,then i go back login form page,it also need i input username password,how can i correct it ?
Ben | November 4th, 2008 at 9:08 pm #
Hi,
When I try and connect i get the two cannot connect words, What does this mean?
Thanks
Robindrost | November 16th, 2008 at 7:59 pm #
Thanks for this great login script!