Tutorial: PHP/mySQL Membership System
Posted by Pat
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 :D.
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!
June 12th, 2008 at 11:00 am
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
June 24th, 2008 at 8:42 am
Thanks for this tut! If I use this I will put link to this tutorial!
June 24th, 2008 at 8:43 am
Ahh, Administrator are will be good thing!
June 24th, 2008 at 10:25 pm
This is best
June 28th, 2008 at 10:11 am
Thanks a lot! Very well explained and just what I needed. Thumbs up ^^.
June 30th, 2008 at 5:32 pm
Thanks… Great help.
July 3rd, 2008 at 5:18 am
i just get an access denied error
July 7th, 2008 at 2:27 pm
To: Stephen
Have you modified the script at all? Are you using the correct database information?
July 8th, 2008 at 3:53 pm
Can you possibly include the mySQL database setup?
July 9th, 2008 at 12:40 am
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!
July 9th, 2008 at 12:48 am
To: Harrison + Anthony
Please view the updated tutorial for the mysql setup.
July 10th, 2008 at 1:03 am
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!
July 10th, 2008 at 10:42 am
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.
July 10th, 2008 at 1:15 pm
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’
July 10th, 2008 at 2:35 pm
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
July 13th, 2008 at 7:32 am
Hey pat,
I get a problem with the syntax when i try registering. Could you help me out?
Thanks Ryanhami
July 14th, 2008 at 12:49 am
Good Tutorial
July 18th, 2008 at 10:14 am
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!
July 26th, 2008 at 5:53 pm
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
July 27th, 2008 at 4:24 pm
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
July 29th, 2008 at 11:05 am
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?
July 29th, 2008 at 11:15 am
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…
July 30th, 2008 at 12:56 am
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.
August 3rd, 2008 at 5:30 pm
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.
August 8th, 2008 at 7:32 am
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
August 13th, 2008 at 12:58 am
Just what i was looking for. Thanks so much for this tutorial. Keep up the good work!
August 13th, 2008 at 1:01 am
@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.
August 15th, 2008 at 11:36 am
Thank you!
August 20th, 2008 at 5:39 am
do not use this tutorial, everyone is having problems with it - and it doesn’t work. Waste of time.
September 1st, 2008 at 8:44 pm
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?
September 6th, 2008 at 8:00 am
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
September 9th, 2008 at 5:05 am
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
September 14th, 2008 at 9:13 am
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.
September 15th, 2008 at 12:58 pm
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?
September 15th, 2008 at 6:03 pm
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 ?
September 15th, 2008 at 6:04 pm
like odC says. got the same problem
September 16th, 2008 at 12:55 am
Phenomenal tutorial! Thank you so much for taking the time to share your knowledge. It is much appreciated!
September 19th, 2008 at 8:54 am
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
September 24th, 2008 at 4:46 pm
Grrrrreeeeeeeeaaaaaaaattttttt !!!!!!!!
October 12th, 2008 at 7:59 pm
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?
October 20th, 2008 at 8:33 pm
This is awesome. Would love a forgotten password feature.
October 21st, 2008 at 4:09 am
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??
October 22nd, 2008 at 7:46 pm
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.
October 26th, 2008 at 6:01 pm
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.
November 15th, 2008 at 5:58 am
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.
November 15th, 2008 at 6:38 am
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.
December 22nd, 2008 at 1:43 pm
Thanks! This is the first tutorial of its kind that has actually worked for me! Thank you again!
January 4th, 2009 at 9:39 pm
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
January 7th, 2009 at 12:54 pm
(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.
January 11th, 2009 at 11:26 am
man you have you done great job for the people who are just beginerzz … you are a star
keep helpinn man thanks alot..
January 23rd, 2009 at 4:52 am
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?
January 26th, 2009 at 4:37 pm
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.
February 9th, 2009 at 1:37 pm
Luke can u make a detailed tutorial about referal link,id… i really need one. Thank’s
March 19th, 2009 at 11:45 pm
i found your script very good but is there a way to have php code on the page requiring logins?
March 26th, 2009 at 8:39 pm
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!
April 13th, 2009 at 7:57 am
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!
May 5th, 2009 at 11:12 pm
Very cool, finally got it to work.
June 3rd, 2009 at 1:44 pm
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
June 19th, 2009 at 6:52 am
che - change the field type to password to mask it
i.e
echo “Password:”;
June 19th, 2009 at 6:53 am
sorry - code in post borked the post
input name=”password” size=”18″ type=”password”
July 9th, 2009 at 4:03 am
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!
September 10th, 2009 at 4:49 am
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
October 31st, 2009 at 6:59 pm
looooooooooooooooooooooooooooooooove iiiiiiiiiiiiiiiiiiiiiiiiiit!!!!!!!!!!!!!!!!!!11
January 25th, 2010 at 5:06 am
For administration use phpMyAdmin
February 27th, 2010 at 4:04 pm
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
April 14th, 2010 at 6:05 pm
Funny, I remember writing this article for CaliScape.net over a year and a half ago…
I only just recently posted it on my blog: http://blog.neilhanlon.com/2010/03/22/member-area-tutorial-php-mysq/
Care to explain?
Thanks,
Neil Hanlon
NeilHanlon.com