Hi, today I am going to show you how to make a simple membership system. This included, registering for an account, logging in, security for pages, and logging out.
Now shall we begin? I say yes!
Our database will be setup like the following:
1 2 3 4 5 6 7 | CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL auto_increment, `username` varchar(225) NOT NULL default '', `password` varchar(225) NOT NULL default '', `email` varchar(225) NOT NULL default '', PRIMARY KEY (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; |
Breakdown:
user_id is the default value that keeps track of users.
username is the users log in name.
password is the users log in password.
email is the users email, so in later versions of the member system, a forgot password can be added.
Our 1st bit of code will be a file named conf.inc.php. This file holds all of our mysql and function data, so we don’t have to enter it over and over
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php $db_user = ""; // Username $db_pass = ""; // Password $db_database = ""; // Database Name $db_host = ""; // Server Hostname $db_connect = mysql_connect ($db_host, $db_user, $db_pass); // Connects to the database. $db_select = mysql_select_db ($db_database); // Selects the database. function form($data) { // Prevents SQL Injection global $db_connect; $data = ereg_replace("[\'\")(;|`,<>]", "", $data); $data = mysql_real_escape_string(trim($data), $db_connect); return stripslashes($data); } ?> |
Breakdown:
The 1st part is all the mySQL information in order to view and insert data.
The 2nd part prevents SQL injection, so people cant gain unauthorized access.
Our next file will be register.php, it will allow users to register an account so they may login and view parts of the website that others cant.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <?php include("conf.inc.php"); // Includes the db and form info. if (!isset($_POST['submit'])) { // If the form has not been submitted. echo "<form action=\"register.php\" method=\"POST\">"; echo "<table>"; echo "<tr>"; echo "<td colspan=\"2\">Register:</td>"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Username:</td><td width=\"50%\"><input name=\"username\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Password:</td><td width=\"50%\"><input name=\"password\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Email:</td><td width=\"50%\"><input name=\"email\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"submit\"</td>"; echo "</tr>"; echo "</table>"; echo "</form>"; } else { // The form has been submitted. $username = form($_POST['username']); $password = md5($_POST['password']); // Encrypts the password. $email = form($_POST['email']); if (($username == "") || ($password == "") || ($email == "")) { // Checks for blanks. exit("There was a field missing, please correct the form."); } $q = mysql_query("SELECT * FROM `users` WHERE username = '$username' OR email = '$email'") or die (mysql_error()); // mySQL Query $r = mysql_num_rows($q); // Checks to see if anything is in the db. if ($r > 0) { // If there are users with the same username/email. exit("That username/email is already registered!"); } else { mysql_query("INSERT INTO `users` (username,password,email) VALUES ('$username','$password','$email')") or die (mysql_error()); // Inserts the user. header("Location: login.php"); // Back to login. } } mysql_close($db_connect); // Closes the connection. ?> |
Breakdown:
We 1st include the database details and make sure the form has not been submitted. If it has not been submitted then we display the register form.
If the form is submitted, we make some variables so we can incorporate the form() function.
We then make sure that the users email or user name are not already in the database.
Then we insert the user into the database and redirect them to the login page.
The next page is login.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php include("conf.inc.php"); // Includes the db and form info. session_start(); // Starts the session. if ($_SESSION['logged'] == 1) { // User is already logged in. header("Location: index.php"); // Goes to main page. exit(); // Stops the rest of the script. } else { if (!isset($_POST['submit'])) { // The form has not been submitted. echo "<form action=\"login.php\" method=\"POST\">"; echo "<table>"; echo "<tr>"; echo "<td colspan=\"2\">Login:</td>"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Username:</td><td width=\"50%\"><input name=\"username\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Password:</td><td width=\"50%\"><input name=\"password\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"submit\"</td>"; echo "</tr>"; echo "</table>"; echo "</form>"; } else { $username = form($_POST['username']); $password = md5($_POST['password']); // Encrypts the password. $q = mysql_query("SELECT * FROM `users` WHERE username = '$username' AND password = '$password'") or die (mysql_error()); // mySQL query $r = mysql_num_rows($q); // Checks to see if anything is in the db. if ($r == 1) { // There is something in the db. The username/password match up. $_SESSION['logged'] = 1; // Sets the session. header("Location: index.php"); // Goes to main page. exit(); // Stops the rest of the script. } else { // Invalid username/password. exit("Incorrect username/password!"); // Stops the script with an error message. } } } mysql_close($db_connect); // Closes the connection. ?> |
Breakdown:
1st we include the db and function file, and start the session, telling the browser that sessions will be used.
We then make sure the form has not been submitted in order to show the login form.
If the form has been submitted we make 2 variables for user name and password. We encrypt the password with md5() so it is a bit more secure. (To all those who are experts in PHP, you would normally salt a password to make it harder to crack, but for beginners stick with md5())
We then have a query checking the database if any users match the use rname and password, and if there are matches it will be counted in $r.
If there are matches we set a login session.
Now we will make logout.php.
1 2 3 4 | <?php session_unset(); // Destroys the session. header("Location: login.php"); // Goes back to login. ?> |
Breakdown:
We destroy all sessions and forward the user to the login page.
And last but not least, the page where you want only logged in users to view.
1 2 3 4 5 6 7 8 9 10 11 | <?php include("conf.inc.php"); // Includes the db and form info. session_start(); // Starts the session. if ($_SESSION['logged'] != 1) { // There was no session found! header("Location: login.php"); // Goes to login page. exit(); // Stops the rest of the script. } echo "This is the main page!"; echo "<br />"; echo "<a href=\"logout.php\">Logout?</a>" ?> |
Breakdown:
We include the config page.
Check to see if the logged in session is set, otherwise forward user to login page.
Allow the user to log out if needed.
Well thats the basic member system, I will add as people request more. If you have any questions please feel free to comment or contact me, I am more than happy to help!
Wow, thanks dude. I needed one for my clan, and I put this into effect. Maybe you can make an admin area with user admin so you can control users. And also maybe a forget password. Thanks
Thanks for this tut! If I use this I will put link to this tutorial!
Ahh, Administrator are will be good thing!
This is best
Thanks a lot! Very well explained and just what I needed. Thumbs up ^^.
Thanks… Great help.
i just get an access denied error
To: Stephen
Have you modified the script at all? Are you using the correct database information?
Can you possibly include the mySQL database setup?
Wow, this seems great! I know NOTHING about php and desperately need a login script for a new website. I will try to learn this. I second the request for a mySQL database setup. Thanks!
To: Harrison + Anthony
Please view the updated tutorial for the mysql setup.
This is great! One question: is this hack proof or user session spoof proof? Once SQL returns a row $r=1, he can be any users. Is that right? What s/b done so that userid can be tied to the session so a user can only see his / her own information / data?
Thank you so much!
To Alex
Yes its secure, because it matches the user name and password, so unless there is duplicate entries you are fine. You can also add a LIMIT 1 to the query to be safe also.
If you want to save the users id to a session, just query the user name and password, and fetch the data, and insert it into the session. You can also do this to other data as well.
Hey Pat, Great tutorial… the notches on your belt are really starting to show.. Thanks for such good work. Just one little request.. I see somone has already requested it but is there any way that you could mod it and add an admin role? That would be absolutely awesome..
Thanks in advance
Andre’
I dont know what the issue is but I keep getting
Notice: Use of undefined constant logged – assumed ‘logged’ in C:\www\vhosts\localhost\test\login.php on line 7
Notice: Undefined index: logged in C:\www\vhosts\localhost\test\login.php on line 7
Notice: Use of undefined constant ’submit’ – assumed ‘’submit’’ in C:\www\vhosts\localhost\test\login.php on line 15
Hey pat,
I get a problem with the syntax when i try registering. Could you help me out?
Thanks Ryanhami
Good Tutorial
Great tutorial!
I run into a couple problems, though.
In the case of a site that’s already designed and utilizes php includes for a header.php file that contains html and page style information, how do you work around this? When inserting the scripts into pages, you either have to insert them before the include(‘header.php’); and have the page render poorly, or have the script not work at all. I attempted to modify it to put include(‘header.php’); within the scripts, but that seemed to be hit-or-miss and I frequently got errors anyway.
Also, how would you place a member login console on a navigation bar that changed depending on the state of the session? In other words, if the user is logged in, your navigation pane says “Username is currently logged in. Logout?”, or “Login or Register” if no user is logged in.
These are probably stupid questions, but despite cursory knowledge of PHP/MySQL, I’m completely unfamiliar with user authentication. Having said that, I do appreciate your tutorial very much. It was well written and well presented (though there were a couple typos in code here and there). You made concepts that I’ve been struggling with the past few days seem very straight-forward. Well done!
Hey Andre and Pat,
I am getting a similar error Andre got – on his post on july 10th. If you’ve figured it out could you please post it here. Thanks a lot!!!
Here are the errors I am getting:
Notice: Use of undefined constant ‘logged’ – assumed ‘‘logged’’ in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\login.php on line 4
Notice: Undefined index: ‘logged’ in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\login.php on line 4
Notice: Use of undefined constant ’submit’ – assumed ‘’submit’’ in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\login.php on line 8
For the admin area, i think i may know how. Just add an aditional field in your users table named something like accesslvl then when somepne wants to view that page, set up a mysql querry. here is the querry: “select * from users where username = “session user” and accesslvl = “admin”
Of course where it says “session user” it is not literal. i am not sure how u would refer to it and u can change admin to whatever you want. then u just have to put something like this in your php script
$sql = querry from above;
$result = my_sql_querry($sql);
if ($result = 1)
{
?>
and it goes on
not sure if the syntax for the $result is right, but it should work. Hope it works, i have yet to try it out
For some reason when I login through login.php, it submits my credentials but redirects me back to login.php. I changed the line:
header(“Location: index.php”);
to
header(“Location: members.php”);
And I swapped the index.php for members.php everywhere else. Still, it doesn’t redirect me there, nor does it give me the “Incorrect username/password!” message. I assume since I’m not getting this error that the credentials work, but it is not redirecting me correctly.
Any ideas?
Okay, scratch that. I went through my files and replaced the single-quotes surrounding the variables with regular single-quotes.
Now I get an error, “Can’t connect to MySQL server on ‘localhost’ (10061),” so I gotta figure out why it’s not connecting to my database…
I can’t seem to get this to work. When submitting my username and password on the home page, it takes me back to the same page even though I know this username and login are in the db. Even if I put in a bogus login, it doesn’t even show an error.
Yeah I have the same problem as Matt, no matter what I do it doesn’t seem to want to continue it just brings me back to the same page with an empty form.
i have entered this code into my phpmyadmin sql area
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL auto_increment,
`username` varchar(225) NOT NULL default ”,
`password` varchar(225) NOT NULL default ”,
`email` varchar(225) NOT NULL default ”,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and this error shows
MySQL said:
#1064 – You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘â€
any help would be great
Just what i was looking for. Thanks so much for this tutorial. Keep up the good work!
@paul, may be some problem with the charset of the statements you entered. Don’t just copy and paste the codes from here. Try typing it yourself. IMO, the problem is with the quotation marks.
Thank you!
do not use this tutorial, everyone is having problems with it – and it doesn’t work. Waste of time.
Hey very nice code, but i have a question. I am a game developer and not very good at php and I am going to be using a SMF as my support forum for the game I have coming out sometime in 2009, and I want to get it so that when I login at the website it as well will login at the forum. So how would I go about doing that? Wouldn’t it just be a simple change in the forum’s own mysql login and regestration script?
I get this error, any help?
Warning: Cannot modify header information – headers already sent by (output started at /var/www/vhosts/arnoldtang.net/subdomains/development/httpdocs/login/conf.inc.php:17) in /var/www/vhosts/arnoldtang.net/subdomains/development/httpdocs/login/register.php on line 39
Hi,
I tried with the code you have provided but I am not getting the desired output. My index.php redirects to login.php but after giving username/password (via browser) it keeps on saying “Incorrect Username/password”.
I even created a test user in db (via mysql prompt) but still the user is not autenticated through browser.
Any guess what might be wrong?
Bharat
WoW, This is what i’ve been looking for!
Finaly a very good and complete auth script using php/mysql, encryption, session, etc.
Even is somes people are reporting some bugs in here.. even a beginner php coder should be able to fix it in order to make it works.
- No dumb auto-install script that you understand anything.
- Easy, keeped simple, clear and short code
- All files very well explained, no headaches reading it.
- Im now one of your fan
For all those who cant make it work, try to retype all singles or double quotes from this tutorial.
If you have problem login in, disable the md5 encryption until you learn more about it.
Good stuff man, thanks!
The only problem I have is that logout doesn’t seem to work for me – I keep coming back to index.php.
My guess is that despite the session_unset() the check in line 4 of login.php returns true and I am redirected to index.
Any way to resolve that?
Great job,
just got one problem.
when i have logged in. and press the log out button,
it goes to login.php BUT i dont see the page, cause i RETURN to index.php where it says this is the main site, (logout?.
can anyone help me ?
like odC says. got the same problem
Phenomenal tutorial! Thank you so much for taking the time to share your knowledge. It is much appreciated!
The problem with not being able to logout is due to the logout page missing the session start. To correct this it should read:
Everything works fine for me now after making this change. Thanks for the tutorial
Grrrrreeeeeeeeaaaaaaaattttttt !!!!!!!!
Wow, this is a nice login script, but you have quite a few errors, and I know why people are getting them. Have you tried this on a webserver yourself?
This is awesome. Would love a forgotten password feature.
Hey pat, i just have one doubt on the table definition, using just user_id as a primary key wouldn’t allow user_name and password to be duplicated??
Lem on Sept 19th posted a solution for the logout. I too am having trouble with the logout. The rest of the script works fine. When I click logout, I’m taken to login.php but I’m stilled logged in. what is Lem’s solution/why was it omitted/deleted?
Also, it’d be cool if there was a password reminder/reset link because the only way i can think to reissue a password now is to use a htpasswd password generator anytime a user contacts me regarding a lost pass…and that is sooo not cool.
either way, thank you for this script. i had been searching all weekend for a solution and i THINK i was able to hard code an integration between this script and paypal ipn so now my site can function like a subscription site which IS cool. thanks again.
oooooooh, sorry had to reread lem’s post. not sure if code posting is allowed but you need to add the first two lines in the login script or in other words, start the session
include(“conf.inc.php”); // Includes the db and form info.
session_start(); // Starts the session.
I was looking at the comments to see if anyone complained on the logout problem, wanted to say about the session_start() forgotten but i see “lem” already answered that.
Great and simple script.
Hey Patt,
Thank you very much for this tutorial.
I am waitin your other lessons.
I would like to learn how i will add, delete, search, update users to my web page.
And secondly how i will change contents of page when i push the css button.(banner and menü will be constant.)
Can you teach again and again thank you so much.
One more question,
I would like to make my layout Css and i would like to put to my css page in another page but you used a function if (!isset($_POST['submit'])) {
.
.
.
else{
so how i can make seperately.Can you advise me?I mean i would like to add and contribute to my Css layout but how i can thank you.
Thanks! This is the first tutorial of its kind that has actually worked for me! Thank you again!
Hello Pat, beautiful script for beginners
But, by the way, I dont know if this is an PHP 5+
issue or an typo in your code but in logout.php
the session_unset by itself doesnt work.
After searching php.net I found that I had to
start the session again, unset it and then destroying it. Like that:
session_start();
session_unset();
session_destroy();
From a comment at:
http://gr.php.net/manual/en/function.session-unset.php
That worked
But still, you rock
that “error”
utilize me to think a little more
(login,php) I get a Warning: session_start()[function.session.start]: Can not send session cookie – headers already sent by (output started at g:\authenticarre\conf.inc.php:16) in c:\authenticate\login.php on line 3.
I did a copy and paste only adding the correct MySQL information.
The register.php returns pretty much the same warning however the name is added to the database.
BYW the black on gray is brutal on us old folks.
testing under xampp for Windows on a thumbdrive.
man you have you done great job for the people who are just beginerzz … you are a star
keep helpinn man thanks alot..
Hi guys!
I just keep getting the error message “There was a field missing, please correct the form.” when I have filled out the form and hit submit on register.php
Anyone knows whats wrong?
Very nice, easy to follow, and well commented. Even for someone with no PHP/SQL experience I can fully understand the entire thing. I even added my own feature which is allowing users to refer people!
I added this…
$refby = $_GET['ref']; //who refered you
so for example your friend tells you to goto http://www.yoursite.co.uk/register.php?ref=Luke the user Luke would be stored in $refby which can be used later like this.
mysql_query(“UPDATE users SET ref_amount = ref_amount + 1 WHERE username = ‘$refby’”) or die (mysql_error());
I added a new field into the database (obviously an int) called ref_amount which stores the referral amount, upon sign up the referral amount increased by one each time (tested and worked!) i also made it so the user couldn’t refer themselves. I cba to put that in here at the moment.
Luke can u make a detailed tutorial about referal link,id… i really need one. Thank’s
i found your script very good but is there a way to have php code on the page requiring logins?
how come the password comes out as a letter when you type it on the login page and register page? and the log out is forbidden when i click the logout button. pls help! thanks!
i havnt read all the comments so this may already have been poited out. However this script worked 99% effectively. the logout button doesnt work. if anyone else has had this problem simply include session_start(); at the beggining of the log in page!
Thanks for the great php!
Very cool, finally got it to work.
thank you sean for pointing this out!! it was driving me nuts
my eyes skipped right over it.
For everone else who cant ‘logout’ on the main page, add session_start() at the very top of the LOGOUT page, not login page
just under the <?php
Thank you for the tutorial
che – change the field type to password to mask it
i.e
echo “Password:”;
sorry – code in post borked the post
input name=”password” size=”18″ type=”password”
Cool features. It would be even nicer to have a forgotten my password script, admin section and hide password when logging in ******.
But i will discover myself those.
Thanks!
Hello,
I keep getting an error:
There was a field missing, please correct the form.
Obviously I leave no blank field upon submitting the form, somehow I get this error regardless…
cheers
Greg
I keep getting this error on the login page…
Warning: Cannot modify header information – headers already sent by (output started at /home2/eoldhamn/public_html/mgymnastics/memeber/conf.inc.php:2) in /home2/eoldhamn/public_html/mgymnastics/memeber/login.php on line 33
I also get it on register page….
Warning: Cannot modify header information – headers already sent by (output started at /home2/eoldhamn/public_html/mgymnastics/memeber/conf.inc.php:2) in /home2/eoldhamn/public_html/mgymnastics/memeber/register.php on line 39
here is my con.inc.php file…
<?php
$db_user = “eoldhamn”; // Username
$db_pass = “741984″; // Password
$db_database = “eoldhamn_address”; // Database Name
$db_host = “localhost”; // Server Hostname
$db_connect = mysql_connect ($db_host, $db_user, $db_pass); // Connects to the database.
$db_select = mysql_select_db ($db_database); // Selects the database.
function form($data) { // Prevents SQL Injection
global $db_connect;
$data = ereg_replace(“[\'\")(;|`,]“, “”, $data);
$data = mysql_real_escape_string(trim($data), $db_connect);
return stripslashes($data);
}
?>
looooooooooooooooooooooooooooooooove iiiiiiiiiiiiiiiiiiiiiiiiiit!!!!!!!!!!!!!!!!!!11
For administration use phpMyAdmin
Srry I have a question I’m stuck with where would I save my database so the blog can access it. And is there anything I need to enable in the php.ini file.
thanks
It’s amazing how you work, Thanks a lot.
Thi is great. Appreciate the hardwork. I am a newbie and I am trying to create a mod to your registration script. I would like to have the script populate the form and then permit changes. Obviously, I am not doing it correctly. Wondering if you might have a sample of same.
Thanks.
Thanks for the tutorial.
Your tutorial was very helpful although I have an additional level of security that I hope I can introduce into the code.
I am providing a service to a vertical market. My customers are the businesses that have subscribed to my service. The users are employees of those businesses.
I have a table with my customers (businesses) that has a company code and a company name.
I also have a user table that contains all the fields specified in your tutorial plus an additional field, company code. This table contains all users for all companies.
When a user logs in, they need to be prompted for their company code, their username, and their password. I added the check for company code, using the same format as used for the other fields, followed by the code for user and password.
The login will accomplish two purposes. The first is authentication. The second is to identify the user with my customer, the company. This will insure that users of one customer do not have access to user or customer information from other companies.
Do you see any problem with the logic I described above?
Thanks.
Great but how do i remove members?
Hello,
I would like to use the above tutorial. I noticed that it was posted in 2008. Are there any changes that need to be made in the code? Any updates?
[...] PHP/MySQL Membership System [...]
please everything seems to work alright but i do receive this error when ever i login to the users page…please help me
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/a4656106/public_html/login/usersOnline.php on line 21
if possible please provide me with how to authenticate each page i want to protect