PHP Login System
21/09/2007 at 19:53:56
Posted by Harry
Hi everyone. In this tutorial I will tech you how to make a PHP login form using sessions. You will need four files, one named form.php, one named login.php, another named auth.inc and the last named protected.php
NB these names can be changed at your will, but make sure you rename them throughout the tutorial.
Step 1)Open a blank document in Notepad and type the following:
Listing 1.1 – form.php<head>
<title>Login Form</title>
</head>
<body>
<form method="post" action="login.php">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Login" /><br />
</form>
</body>
</html>
Save this file as form.php.
Here we have set up a simple form that will pass submitted information onto the file login.php.
Step 2)Now open a second blank document in Notepad and enter the following:
Listing 2.1 – login.phpsession_start();
$passwords = array("harry" => "dirtyharry",
"george" => "gorgieboy01",
"bob" => "bigbobby",
"jack" => "jackthelad");
if (!$_POST["username"] or !$_POST["password"]) {
echo "Please enter your username and password.";
exit;
}
if ($_POST["password"] == $passwords[$_POST["username"]]) {
echo "Login successful!";
$_SESSION["auth_username"] = $_POST["username"];
}
else {
echo "Login incorrect, please try again.";
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
Content in here will only be shown if the username and password supplied are correct.
</body>
</html>
Save this file as login.php.
Notice the php script comes before even the <html> tags. This ensures that the php is executed before the page gets rendered, so if the credentials were wrong the offender cannot see anything protected.
Basically here we tell the browser to start a session to store usernames and passwords in. We then set up an array called passwords which contains a list of usernames and respective passwords, from Harry to Jack.
The next part of the script checks inequality between the submitted credentials and the known credentials. The exclamation mark means “Does not equal”. If the credentials are indeed false/incorrect the script will display the message “Please enter your username and password.” One the users screen. The exit; function stops the script from continuing as soon as incorrect details are given.
The following section of the script checks for equality inequality between the submitted credentials and the known credentials. The double equals checks for equality, whereas a single equals assigns a value to a variable. If the credentials are correct the script displays "Login successful!" on the users screen. Then a session is started called “auth_username”. This allows the browser to remember whether or not a user is logged in, which means that they will not have to login again on a different page.
The final part of the php covers all other eventualities and displays "Login incorrect, please try again." to the user.
The rest of the page is shown below, between the <html> tags. The message between the <body> tags will not be visible unless the user is logged in.
Step 3)You have pretty much finished creating a php secure login, but to illustrate the functionality of sessions, you may want to continue through Step 3.
Open your third document in notepad and type the following:
Listing 3.1 – auth.incsession_start();
if (!isset($_SESSION["auth_username"])) {
echo "You must be logged in to view this page";
exit;
}
else {
echo "Hello, you're logged in!";
}
?>
auth.inc stores the information related to your session. You could type the above in every document, but it would become cumbersome and annoying. By including it using php you only need type it once and pull it in using the include function, as shown below.
The final script, protected.php, will be an arbitrary page that you wish to secure.
Listing 3.2 – protected.phpinclude "auth.inc";
?>
<html>
<head>
<title>Protected Page </title>
</head>
<body>
Content in here will only be shown if the username and password supplied are correct.
</body>
</html>
If you want to protect any further pages you simply need to add the include function at the very top of every page.
P.S. This script is not intended for protection of highly confidential documents, but rather for client extranets etc.
Download the tutorial files.
31 comments
Nick - 23/09/2007 at 01:29:23
I would recommend adding a session. Currently it allows you to login if the session auth_username is correct and exists. However, session stealing can still occur ><
I have no ideas how session stealing works, but it does. All you need do is when the session auth_username is created, create another session matching the users ip to session auth_ip for example, then check it in auth.php.
Just a little advice :P I started php only a few months ago, it takes a lot of hard work and by the looks of it, you're doing amazingly ;)
Harry - 23/09/2007 at 12:16:03
Nick, thanks! Great advice, I'll look at that. Does it basically reference the IP against the credentials, making sure someone in China isn't using the password of someone in the US?
I only started about 2 months ago, still a lot to learn.
Martin Davidson - 25/09/2007 at 10:37:58
Truly Awesome
Al Fox - 28/09/2007 at 15:24:43
Great tutorial Harry. It is actually quite simple to associate the users IP with the Session. It could be as simple as, upon login, defining the IP in a variable.
$_SESSION['authip'] == $_SERVER['REMOTE_ADDR'];
and then simply check it against the users IP on every page.
if ($_SESSION['authip'] != $_SERVER['REMOTE_ADDR']) {// the world ends } else { proceed with stuff }
(just an example).. Great post!
Tim - 08/10/2007 at 22:41:35
Nice job! I was looking for something like this.
For the person who posted above or anyone else who may know. Not sure where or how to add associateing users with IP in the script. Any more insight on that?
Thanks!
Andy - 01/12/2007 at 22:30:16
Excellent work!! Been looking on the internet for hours and this is by far the quickest and best simple login system I have come accross.
Keep up the good work :-)
Harry - 02/12/2007 at 23:40:44
Andy, don't mention it!
mack - 17/12/2007 at 19:41:38
If you must store passwords in plain view, you should consider hashing them with md5() first. Then, when the user attempts to auth, you hash their input and compare it to the stored hash.
e.g.
//MD5 ("dirtyharry") = a6e268749faf07df56091b1317f9544a
//outputs "dirtyharry"
echo $_POST["password"];
//hashes the input password, dirtyharry, then compares it to the stored hash (shown above)
if(md5($_POST["password"]) == $passwords[$_POST["username"]]) ...
It's not totally secure, but it definitely helps if you're working on a page where multiple users can potentially view your source through FTP/SSH/etc.
Erm - 18/12/2007 at 07:39:06
... anyone can view auth.inc from a browser. Maybe it'd be smart to name it auth.inc.php so the code is executed.
It just seems to me. to allow people to view code from the browser isn't smart.
bert - 19/12/2007 at 00:58:13
Could be wrong here, but...
I think I can see a potential hole.
if ($_POST["password"] == $passwords[$_POST["username"]]) {
I would change to:
if (array_key_exists($_POST["username"], $passwords)
&& $_POST["password"] === $passwords[$_POST["username"]]) {
That way, if a username was entered that did not exist in the $passwords array, this if condition would not be checking an empty array element against the entered password.
Hmmm. Think I got that right!?
Harry - 19/12/2007 at 12:41:20
Wow, I thought this post was dead and buried lol. I have since developed a more secure method of doing the above, using encrytion and a php include as opposed to a .inc one.
Rob - 20/12/2007 at 01:34:58
Do you know how to do a "Leave a comment" section, without using Wordpress?
Best Regards
Rob
Harry - 20/12/2007 at 09:12:54
Rob - Here: http://labs.prdesign-studio.co.uk/category/php/commenter/
Ryan - 16/01/2008 at 21:01:14
Dude, i have been looking for a decent login tutorial for php and have come up with nothing until now.
Thank you for your help!
Harry - 17/01/2008 at 10:58:58
Glad you liked it.
Ian Regan - 20/01/2008 at 21:18:27
This looks like a really good script, but I'm having a problem - even if I enter an incorrect username and password, the login.php page renders the following in the browser:
"Login incorrect, please try again. Content in here will only be shown if the username and password supplied are correct."
It seems that the html code at the bottom of the page is displayed regardless of the php code before it.
Despite this flaw, the protected.php script seems to work fine. Can anyone explain why the login.php doesn't seem to work properly? Thanks.
Brandon - 22/01/2008 at 00:36:56
Nice just in case you would like a login script that is GPL and offers an admin section with edit user features and is based on the Smarty templates system check out mine. Great job Harry . http://sourceforge.net/projects/openauto/
Harry - 22/01/2008 at 14:44:15
Ian: That's my bad I'm afraid. That html will always be shown on that page. Sorry for the mess up.
Harry
Ian Regan - 22/01/2008 at 20:21:02
No worries Harry - I got the result I wanted by including the auth.php file inside all the pages I wanted to protect. Works a treat. Thanks!
Harry - 23/01/2008 at 17:08:52
Ian: Good, glad it worked ok.
John - 25/03/2008 at 10:15:52
I read somewhere that it is not smart using "name" attributes in the login form, but instead "id" is better. reason is because "name" attributes allows users to store passwords which is not a good idea.
John - 25/03/2008 at 12:04:04
I read somewhere that it is not smart using "name" attributes in the login form, but instead "id" is better. reason is because "name" attributes allows users to store passwords which is not a good idea.
Delroy - 16/04/2008 at 22:26:15
I really love your tuts
i just started php and man i really love it, i just keep reading what you guys suggest and learning,,, you guys are my teacher.. so keep it coming
Harry Roberts - 30/04/2008 at 17:22:49
Glad it's helping Delroy!
etur - 08/05/2008 at 00:10:42
very cool script :) i'm very new @PHP and i've looked far for something like this. thank you again.
etur - 08/05/2008 at 00:14:01
by the way, how can i fecth the $username and display directries according to the value?
Anderson - 19/06/2008 at 13:11:06
Hi guys. Good script. I just want to ask if it's possible to use email instead of username. Also how to chech the email form if it contains the @example.com.
Anderson - 19/06/2008 at 14:11:01
Hi guys. Good script. I just want to ask if it's possible to use email instead of username. Also how to chech the email form if it contains the @example.com.
Daniel - 02/07/2008 at 01:56:55
Thanks for the script I really needed some help with login forms! Is it possible to add a page for Member stuff?
Matt - 21/09/2008 at 00:33:06
Very unsecure script. The admin knows everyone's passwords, and has to manually enter then. it's fine if you are the only one using it, but need some automation so no one but the user who put it there's password is known. Use mySQL and PHP to build a real login script.
Recent Work...
flick - 22/09/2007 at 10:33:46
awesome, just awesome, well done mate (and he says he's only just started dabbling in php, pah!)