Introduction.
In this tutorial I will be showing you how to create an advanced PHP/MySQL membership system for you’re website. We are going to create the simple forms, and create the back end to allow users to login, register, and logout of you’re website.
This “Advanced” membership system is actually quite simple, what makes it advanced is the object oriented user that will allow for a very extendable membership system. This makes the membership system very versatile and usable on many different kinds of website.
You will need:
- A little bit of PHP knowledge.
We will be using some object oriented programming along with the basic required PHP for the membership system. - HTML Knowledge.
I am just going to give code for basic forms just to make the scripts work. - A Text Editor or IDE.
You will obviously need some sort of editor to edit your files in. - A testing server.
You will need somewhere to test your project, we will be using PHP and MySQL so ensure that you’re testing server has these services available.
Create the basic files.
We are just going to create the HTML forms and files that we are going to use to access the membership system. We need to make one for existing users to login, that one will be simple because it is just 3 elements. Email/Username, Password, and Submit. We also will need to make a register form to allow new users to register on your website.
The files we will need in the root directory will be:
- index.php
The main page that the users will access. Will also include the Login form. - register.php
The form for users to register into the website, if this is something that you want. - handlers/login_handler.php
Will handle a login request by the user, check it against the database, and authorize or deny the login request. - handlers/register_handler.php
Will handle a request by the user to register to the website. - handlers/user_handler.php
Will be included in the beginning of all of your pages to load the users settings. Will also check the page permissions against the users permissions. - handlers/User.class.php
This is the actual user class. This will hold all of the users information and provide different functions relating to the membership system.
Create the forms.
The forms you will want to customize to match you’re websites theme. I am just going to give you basic forms to get the tutorial running, and the HTML isn’t what this tutorial is really about so we are just going to skip over the HTML basics there.
Login Form (plus some php code for later):
<?
php
require("handlers/user_handler.php");
if($user_data['loggedIn'] == 1)
{
$
string
=
"Logged in as: "
;
$string .= $User->get_info("email");
$string .= " <
a
href=?logout>Logout</
a
>";
echo $string;
}
if(isset($_GET['error']) && $_GET['error'] == 1)
{
echo "<
span
style
=
color
:red>There was an error logging in!</
span
>";
}
?>
<
form
id
=
"login"
method
=
"POST"
action
=
"handlers/login_handler.php"
>
Email: <
input
type
=
"text"
name
=
"email"
/><
br
/>
Password: <
input
type
=
"password"
name
=
"password"
/><
br
/>
<
input
type
=
"submit"
name
=
"submit"
value
=
"Login!"
/>
</
form
>
Put this code into your “index.php” file. This will act as the login form.
Next paste this form (or create you’re own) in “register.php“:
<?
php
if(isset($_GET['error']) && $_GET['error'] > 0)
{
echo "<
span
style
=
color
:red>There was an error registering</
span
>";
}
?>
<
form
id
=
"register"
method
=
"POST"
action
=
"handlers/register_handler.php"
>
First Name: <
input
type
=
"text"
name
=
"first_name"
/><
br
/>
Last Name: <
input
type
=
"text"
name
=
"last_name"
/><
br
/>
<
br
/>
Email: <
input
type
=
"text"
name
=
"email"
/><
br
/>
Password: <
input
type
=
"password"
name
=
"password1"
/><
br
/>
Verify Password: <
input
type
=
"password"
name
=
"password2"
/><
br
/>
<
br
/>
<
input
type
=
"submit"
name
=
"submit"
value
=
"Register!"
/>
</
form
>
Now that the base pages are done (ugly, but done) we can start to get into the back end of the membership system.
Create the MySQL Database.
The database is going to be very simple. A single table in the database will handle everything necessary for the entire membership system to work properly. Like I said in the introduction the “advanced” membership system is actually quite simple.
Create a database:
CREATE
DATABASE
`database_name` ;
Obviously you need to replace “database_name” with the name of the database you are creating, If you’re website is already using a database you can skip that part and just add the table to the database.
Add the table to the database:
Add the table to the database:
CREATE
TABLE
`database_name`.`users` (
`id`
INT
( 10 )
NOT
NULL
AUTO_INCREMENT
PRIMARY
KEY
,
`first_name`
VARCHAR
( 255 )
NOT
NULL
,
`last_name`
VARCHAR
( 255 )
NOT
NULL
,
`email`
VARCHAR
( 255 )
NOT
NULL
,
`
password
`
VARCHAR
( 32 )
NOT
NULL
) ENGINE = InnoDB;
Once again ensure to change “database_name” with the name of the database that you created before (or your existing database). Now that our table has been created we need to insert a default user into the database for testing.
INSERT
INTO
`database_name`.`users`
`id` ,
`first_name` ,
`last_name` ,
`email` ,
`
password
`
)
VALUES
(
NULL
,
'Daniel'
,
'Henry'
,
'daniel@codedopen.com'
,
'aa47f8215c6f30a0dcdb2a36a9f4168e'
);
Now we have a single row in the database holding a user. As of right now there is no user privileges or anything like that. Just a few simple different entries that a website would commonly use. We will get to adding user privileges and more fields later, but this should do for now. Also I should note that the password entry is an Md5 hash. I set the field “password” type to VARCHAR(32) to hold an Md5 hash perfectly, and the users password isn’t stored in plain text.
Starting the back end: User Handler and User Class.
The user handler will be included at the beginning of all of your pages and will determine if a user is logged in already, if not it will allow the user to log in. Otherwise it will load the logged in user from the database, create the user object, and verify the user’s information.
First off lets create the actual user handler:
<!--?php
//include this file at the beginning of every page. //set up mysql mysql_connect("localhost", "root", ""); mysql_select_db("database_name"); session_start(); if(!isset($_SESSION['user'])) { //There is no user logged in $user_data['loggedIn'] = 0; }else{ $user_data = $_SESSION['user']; $user_data['loggedIn'] = 1; //verify that the user data in the cookie //is actually there if($user_data['email'] == "" || $user_data['password'] == "") { unset($user_data); //clear the user data unset($_SESSION['user']); //clear the damaged cookie $user_data['loggedIn'] = 0; //set the user data to read "Not Logged In" } //include the user class require_once("handlers/User.class.php"); if(!$User = new User($user_data['email'], $user_data['password'])) { //user information was invalid. Log user out. unset($user_data); //clear the user data unset($_SESSION['user']); //clear the damaged cookie $user_data['loggedIn'] = 0; //set the user data to read "Not Logged In" } } //check for the logout sequence if(isset($_GET['logout']) && $user_data['loggedIn'] == 1) { unset($_SESSION['user']); unset($user_data); unset($User); $user_data['loggedIn'] = 0; } ?--><?php
//include this file at the beginning of every page.
//set up mysql
mysql_connect(
"localhost"
,
"root"
,
""
);
mysql_select_db(
"database_name"
);
session_start();
if
(!isset(
$_SESSION
[
'user'
]))
{
//There is no user logged in
$user_data
[
'loggedIn'
] = 0;
}
else
{
$user_data
=
$_SESSION
[
'user'
];
$user_data
[
'loggedIn'
] = 1;
//verify that the user data in the cookie
//is actually there
if
(
$user_data
[
'email'
] ==
""
||
$user_data
[
'password'
] ==
""
)
{
unset(
$user_data
);
//clear the user data
unset(
$_SESSION
[
'user'
]);
//clear the damaged cookie
$user_data
[
'loggedIn'
] = 0;
//set the user data to read "Not Logged In"
}
//include the user class
require_once
(
"handlers/User.class.php"
);
if
(!
$User
=
new
User(
$user_data
[
'email'
],
$user_data
[
'password'
]))
{
//user information was invalid. Log user out.
unset(
$user_data
);
//clear the user data
unset(
$_SESSION
[
'user'
]);
//clear the damaged cookie
$user_data
[
'loggedIn'
] = 0;
//set the user data to read "Not Logged In"
}
}
//check for the logout sequence
if
(isset(
$_GET
[
'logout'
]) &&
$user_data
[
'loggedIn'
] == 1)
{
unset(
$_SESSION
[
'user'
]);
unset(
$user_data
);
unset(
$User
);
$user_data
[
'loggedIn'
] = 0;
}
?>
This file is included at the beginning of every page. It pretty much handles everything user related. First it checks to see if a user is already logged in. If a user is already logged in it ensures verifies the information and creates the User object that allows the rest of the website to interact with the logged in user.
With the minimal settings that I have included in the tutorial so far there really isn’t much that you can do with the user but we will talk about expanding the membership system later.
Now the User class:
<?php
//the user class that will hold all of the users informaion
class
User
{
private
$user_information
;
//create a private variable for the users informaion
//that will be loaded from the database.
public
function
__construct(
$email
,
$password
)
{
//the constructor will check the username and password against the database
//and return 1 on success as well as load up the user information.
//create password hash.
$password
= md5(
$password
);
if
(!
$result
= mysql_query(
"SELECT * FROM users WHERE email='{$email}' && password='{$password}'"
))
{
//the user was uncessful with the login
return
0;
}
//put the user information into the "user_information" variable.
$this
->user_informaion = mysql_fetch_assoc(
$result
);
}
public
function
get_info(
$field
)
{
//use this function to get a piece of information that is stored in the database
if
(
$field
==
""
)
{
//there was no requested field
return
0;
}
if
(!key_exists(
$field
,
$this
->user_informaion) ||
$field
==
"password"
)
{
//the requested information does not exist
//or they are requesting the password key.
return
0;
}
if
(!
$request
=
$this
->user_informaion[
$field
])
{
//there was some sort of unexpected error.
return
0;
}
//return the key
return
$request
;
}
}
?>
The User class is in my opinion what makes this membership system advanced. If you were to copy paste this code, yeah, maybe it’s pretty simple. But with some modifications to the code and some customizations to your website this code would allow you to just about anything without really changing too much on the back end of your website.
The class contains a function called get_info(). This function will allow you to grab and return any bit of information on the user except the password key. This will make life much simpler when we get to adding new functionality to your code membership system.
Handling a Login Request.
We will need a file for the login form to direct to. The action of the form that I created points to a file at handlers/login_handler.php. You can put it wherever you want but for the sake of the tutorial we will use the one I listed above. The login handler really doesn’t have to do that much. All it has to do is verify the information and set the session variables.
Login Handler:
<?php
//set up mysql
mysql_connect(
"localhost"
,
"root"
,
""
);
mysql_select_db(
"database_name"
);
session_start();
function
clean(
$string
)
{
//function used for cleaning mysql injection garbage from strings
if
(get_magic_quotes_gpc()) {
$string
=
stripslashes
(
$string
);
}
return
$string
;
}
function
go_home(
$error
=0)
{
//redirect to the form with an error
$string
= "
<script type=\"text/javascript\">
<!--
window.location = \
"../index.php"
;
if
(
$error
== 1)
{
$string
.=
"?error=1"
;
}
$string
.= "\"
-->
</script>
There has been an error logging in, please click <a href=\"../index.php?error=1\">here</a> to go back home.
";
echo
$string
;
die
();
}
if
(!isset(
$_POST
[
'submit'
]) ||
$_POST
[
'email'
] ==
""
||
$_POST
[
'password'
] ==
""
)
{
//ensure that all parts of the form have been filled out.
go_home(1);
}
//create a password hash
$email
= clean(
$_POST
[
'email'
]);
$password
= md5(
$_POST
[
'password'
]);
$result
= mysql_query(
"SELECT * FROM users WHERE email='{$email}' && password='{$password}'"
);
if
(mysql_num_rows(
$result
) < 1)
{
//email or password incorrect
go_home(1);
}
$_SESSION
[
'user'
][
'email'
] =
$email
;
$_SESSION
[
'user'
][
'password'
] =
$_POST
[
'password'
];
go_home();
?>
This file does exactly what I said it should, and really nothing too much more. Not too much advanced stuff to talk about here so we can move on. The only thing that I should mention is now you know how the code above the login form is used. It displays an error on a failed login, and it also displays a “logged in” message when a login is successful.
Handling a registration.
Now all we really need to do to have a complete (but bare) membership system is to add the registration handler. This will be almost as simple as the login handler, it will just be a little bit longer. We need to verify that the email address isn’t already in use, the passwords match, then insert it all into the database. Pretty simple right?
handlers/register_handler.php:
<?php
//set up mysql
mysql_connect(
"localhost"
,
"root"
,
""
);
mysql_select_db(
"database_name"
);
function
clean(
$string
)
{
//function used for cleaning mysql injection garbage from strings
if
(get_magic_quotes_gpc()) {
$string
=
stripslashes
(
$string
);
}
return
$string
;
}
function
go_back(
$error
=0)
{
//redirect to the form with an error
$string
= "
<script type=\"text/javascript\">
<!--
window.location = \
"../register.php"
;
if
(
$error
== 1)
{
$string
.=
"?error=1"
;
}
$string
.= "\"
-->
</script>
There has been an error registering, please click <a href=\"../register.php?error=1\">here</a> to go back to the registration page.
";
echo
$string
;
die
();
}
if
(!isset(
$_POST
[
'email'
]) || !isset(
$_POST
[
'password1'
]) || !isset(
$_POST
[
'password2'
]))
{
//ensure required fields are filled out
go_back(1);
}
if
(
$_POST
[
'password1'
] !=
$_POST
[
'password2'
])
{
//make wure passwords match
go_back(1);
}
//clean the variables
$email
= clean(
$_POST
[
'email'
]);
$password
= md5(
$_POST
[
'password1'
]);
$first_name
= clean(
$_POST
[
'first_name'
]);
$last_name
= clean(
$_POST
[
'last_name'
]);
$result
= mysql_query(
"SELECT email FROM users WHERE email='$email'"
);
if
(@mysql_num_rows(
$result
) > 0)
{
//make sure email is not in use
go_back(1);
}
//insert the user into the database
$query
= "INSERT INTO users
(first_name ,
last_name ,
email ,
password
)
VALUES (
'$first_name'
,
'$last_name'
,
'$email'
,
'$password'
)";
mysql_query(
$query
);
echo
"Successfu Register. Click <a href=../index.php>here</a> to login!"
;
?>
The file creates a new entry in the database after ensuring that a.)The email has not been used yet and b.)that the users passwords match.
Making Additions.
Now that we have a plain jane membership system (Hooray!) we will probably need to start adding to it. First of all the forms need some work and the error handling for the registration and login could be better, but that isn’t our main focus for adding to the membership system.
Mainly what we will want to do is add functionality, like maybe add an address field, phone number, user permissions, etc. This will pe incredibly simple to do because of the way that you build your membership system.
As you know, all you need to do to get any of the users information is use the User objects function get_info() to get a any type of information on the user. So to do something simple like an address or phone number you just need to add them to the database. It will already be loaded into the object after you insert it,
For something like user permissions you would have to add the permissions to the database just like address/phone number, but there would be one more step. You would either have to create a function library to be included with every page, or create methods in the User class to handler user permissions. Either way is fine, I however prefer the latter.
Conclusion.
So after all of that you should have a working membership system on your website. It may have required some tinkering with the code a little bit to get working on your homepage but nonetheless, you learned something new and that it always great.
If you have any problems, errors, or if you see a typo feel free to leave a comment here and I will do my best to help you out. We also have a the forums where you could probably get some support, and I could use some help filling up the boards so if you feel like helping me and also helping start a great new online community for programmers everywhere freel free to stop by.
ليست هناك تعليقات:
إرسال تعليق