Help - Search - Members - Calendar
Full Version: Membership System
Pixel2Life Forum > Member Tutorials and Requests > Forum Tutorial Archives > PHP Tutorials
coldkill
Ok this is my first tutorial but it will cover the following: Logging in; getting the user's information and checking it against what is in the database, Signing up; the key to all that is membership systems, Admin panel; for punishing the heathens and a members panel where they can change their info.

Ok for starters you will need: A server running MySQL and PHP.

OK if you have phpMyAdmin or you can import .sql files or directly use sql to do databasie stuff then use this code to create a table with all the information we need. You can also use PHP to do this but you need to be able to create tables with the username you are using. I'll show both PHP and SQL code for this.

SQL
CODE
CREATE TABLE `members` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 40 ) NOT NULL ,
`password` VARCHAR( 225 ) NOT NULL ,
`email` VARCHAR( 225 ) NOT NULL ,
`avatar` TINYTEXT NOT NULL ,
`level` ENUM( '1', '2' ) DEFAULT '1' NOT NULL ,
`bio` TEXT,
`joined` DATETIME DEFAULT '0000-00-00 00:00:00' NOT NULL ,
`logged` DATETIME DEFAULT '0000-00-00 00:00:00' NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM;


That was the SQL code to insert the table into the database. You can copy it directly into a .sql file (a text file with the extension changed) or if you are using phpMyAdmin there you can use the code on the "Query" tab on your database.

The PHP code is, in all essence, the same as the SQL code since you are running the same query.

But here it is anyway:
CODE
<?PHP
$user = "username"; //change with your username for the database
$password = "password"; //change with your password for the database
$host = "localhost"; //change with the host you have to connect to
$db = "database"; //change with the database name you have access to

//this defines the variable $conn and connects to your database host wether it is localhost or 127.0.0.1
$conn = mysql_connect("$host", "$user", "$password") or die(mysql_error());

//this function selects the database from the host since there maybe more
mysql_select_db("$db", $conn) or die(mysql_error();

/*

the main man/woman in this little sharade.
This defines the variable $sql and executes our query on the database.
If it returns false for some reason wrong password or not enough permissions it will display an error to right your wrongs.

*/
$sql = mysql_query("CREATE TABLE `members` (
                    `id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
                    `username` VARCHAR( 40 ) NOT NULL ,
                    `password` VARCHAR( 225 ) NOT NULL ,
                    `email` VARCHAR( 225 ) NOT NULL ,
                    `avatar` TINYTEXT NOT NULL ,
                    `level` ENUM( '1', '2' ) DEFAULT '1' NOT NULL ,
                    `bio` TEXT,
                    `joined` DATETIME DEFAULT '0000-00-00 00:00:00' NOT NULL ,
                    `logged` DATETIME DEFAULT '0000-00-00 00:00:00' NOT NULL ,
                    PRIMARY KEY ( `id` )
                    ) TYPE = MYISAM;") or die(mysql_error());

//checks the see if the query above returned true if it did it will display "The table etc etc"                    
if($sql){
    echo'The table was successfully added to the database!';
}
?>


Etheir method produces the same table.

Now that we have the first steps out of the way it's time to move onto collecting people's membership details.

First though I suggest you take the following code and put it into a file called db.php it makes like easier instead of writing it out all the time.
CODE
<?PHP
$user = "username"; //change with your username for the database
$password = "password"; //change with your password for the database
$host = "localhost"; //change with the host you have to connect to
$db = "database"; //change with the database name you have access to

// Connects to the database
$conn = mysql_connect( "$host", "$user", "$password" );

// Selects the database we are going to be using
mysql_select_db( "$db", "$conn" );
?>


OK now onto the registering part. First we need a HTML file to submit the information. This file is called join.htm

And it goes a little like this...
CODE
<form name="form1" method="post" action="register.php">
  <table width="100%"  border="0" cellspacing="0" cellpadding="0">
      <tr>
      <td>&nbsp;</td>
      <td>* denotes a required field Note: If no password is entered you will be given a random one which you can change later. </td>
    </tr>
    <tr>
      <td width="12%">Username:*</td>
      <td width="88%"><input name="username" type="text" id="username"></td>
    </tr>
    <tr>
      <td>Password:</td>
      <td><input name="password" type="password" id="password"></td>
    </tr>
    <tr>
      <td><p>Confirm Password:</p>
      </td>
      <td><input name="cpassword" type="password" id="cpassword"></td>
    </tr>
    <tr>
      <td>Email:*</td>
      <td><input name="email" type="text" id="email"></td>
    </tr>
    <tr>
      <td>Confirm Email:*</td>
      <td><input name="cemail" type="text" id="cemail"></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Submit">
      <input type="reset" name="Reset" value="Reset"></td>
    </tr>
  </table>
</form>


You may have noticed that password is not a required field. That is because in the register form we can pick up they have not entered anything and assign them a random password.

Bring on the PHP!

The comments explain all of the bits in detail...

CODE
<?PHP    
//this includes our db.php file with the connection to the database. If it can't find it for some reason it kills the script
require'db.php';
    $email = $_POST['email'];
    $cemail = $_POST['cemail'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    $cpassword = $_POST['cpassword'];
    
    //Check to see if a password has been entered
    if($password){
        //if it has then check to see if confirm password and password fields match
        if(!$password == $cpassword){
            echo '<center><font color=red><strong>Password and Confirm Password do not match! Please enter them again below</strong></font></center>';
            //shows the join form
            include'join.htm';
            //makes sure no other code executes
            exit();
        }
    //if not tell them that they are going to get a random password
    }else{
        echo'<center><font color=blue><strong>You have not entered a password! A random password will be generated for you!</strong></font></center>';
        
        //generates a random password using 7 of the letters and number below
        $salt = "abchefghjkmnpqrstuvwxyz0123456789";
        
        //makes the rand() function more random than normal
        srand((double)microtime()*1000000);
        //declares a variable
        $i = 0;
        //while i is less than or equal to 7 continue otherwise exit the loop
        while ($i <= 7) {
            //generates a random number from the random seed made from srand()
            $num = rand() % 33;
            
            //letter to add to the password
            $tmp = substr($salt, $num, 1);
            
            //adds the new letter to the rest of the password
            $password = $password . $tmp;
            
            /*adds 1 to the variable i if you remove this the loop will continue forever and you'll get an extrememly long password if the server doesnt die on you*/
            $i++;
        }
    }
    
    //same as above if the email field and the confirm email fields dont match then it will display the form again
    if( ! $email == $cemail ){
        echo'<center><font color=red><strong>Email and Confirm Email do not match! Please enter them again below!</strong></font></center>';
        //shows the join form
        include'join.htm';
        //makes sure no other code executes
        exit();
    }
    
    //this checks to see if the user has entered an email address and username
    if( ( ! $email ) || ( !$username ) ){
        echo '<center><font color=red><strong>You did not submit the following required information! </strong></font></center>';
        //checks to see if they have entered an email address
        if(!$email){
            echo "<center><font color=red><strong>Email Address is a required field. Please enter it below.</strong></font></center>";
        }
        //checks to see if they have entered a username
        if(!$username){
            echo "<center><font color=red><strong>Desired Username is a required field. Please enter it below.</strong></font></center>";
        }
        //if not then show the form again
        include'join.htm';
        //and exit the script so nothing else executes
        exit();
    }
    
    //this selects the email address in our table that the user submitted if it finds it
    $sql_email_check = mysql_query("SELECT email FROM users WHERE email='$email_address'");
    
    //this selects the username in our table that the user submitted if it finds it
    $sql_username_check = mysql_query("SELECT username FROM users WHERE username='$username'");
    
    //this checks to see if the above returned true meaning it found the username
    if($sql_username_check){
        
        //this double checks to see if the username was found and if so how many (which should be 1)
        $username_check = mysql_num_rows($sql_username_check);
            
            //If it found more than 0 usernames ie 1 in the table then it displays and error and gets rid of the variable
            if(($username_check > 0)){
                echo "Please fix the following errors: <br />";
            
            if($username_check > 0){
                    echo "<center><font color=red><strong>The username you have selected has already been used by another member in our database. Please choose a different Username!</strong></font></center>";
                    unset($username);
            }
            //show the form... again :(
            include 'join.htm';
            
            //exit the script
            exit();  
             }
    }
    //checks to see if the email check returned true
    if($sql_email_check){
        
        //if so how many email addresses did it find
        $email_check = mysql_num_rows($sql_email_check);            
        
        //if more than 0 display and error and destroy the variable
        if(($email_check > 0)){
            echo "Please fix the following errors: <br />";
        if($email_check > 0){
            echo "<center><font color=red><strong>Your email address has already been used by another member in our database. Please submit a different Email address!</strong></font></center>";
            unset($email_address);
        }
        
        //and show the form to the unlucky user
        include 'join.htm';
        
        //and kill the script
        exit();  
        }
        
    }
    
    //this encrypts the password using md5 hash which cannot be decoded (as far as i know)
    $db_password = md5($password);
    
    //insert the data into our table
    $sql = mysql_query("INSERT INTO members (email, username, password , joined)
            VALUES('$email', '$username', '$db_password', now())");
    
    //checks to see if the data was entered
    if(!$sql){
        echo 'There has been an error creating your account. Please contact the webmaster.';
        exit();
    } else {
        //gets the user's id from the database
        $userid = mysql_insert_id( $conn );
        
        //the subject of the email
        $subject = "Your Membership at My-Website.com!";
        
        //the message remember to change My-Website.com for your url!
        $message = "Dear $username,
        Thank you for registering at our website, http://www.My-Website.com!
        
        You are two steps away from accessing the exclusive members features at My Website!
            
        To activate your membership, please click here: http://www.My-Website.com/activate.php?activate&id=$userid&code=$db_password
        
        Once you activate your memebership, you will be able to login with the following information:
        Username: $username
        Password: $password
        
        You can change your password anytime you log into your account in the Members Area
        
        If you forget your password you can go onto our site and follow the instructions to recieve a new password.
        
        Thanks!
        coldkill
        The Webmaster
        
        This is an automated response, please do not reply!";
        
        mail($email, $subject, $message, "From: My-Website.com<Team@My-Website.com>\nX-Mailer: PHP/" . phpversion());
        echo 'Your membership information has been mailed to your email address! Please check it and follow the directions!';
    }
//closed all mysql connections to save on bandwidth and stuff.    
mysql_close();
    
?>


OK thats the first part of this tutorial. I shall update it soon with the rest of the system!

/coldkill
Nike
This tutorial is almost like Techtuts. But this is a bit more informative.
coldkill
Many people interperit (not too sure if I spelt that right) the manual the same. This is pretty much the standard way of getting data parsed, error checking it and then putting it in the database. Most membership systems etheir derive from or are using this system.

The next part will come soon also smile.gif
Indigo
About when will the next part be up, and what will it contain?
coldkill
It will contain the login and lost password part of the system. It will be up soon.
fRe3zE
err.. were is the rest?
Ruben K
I would like to give a little tip on identifying members by their cookies.
It's not a great idea to match results by means of user_id and password hash combination, I do it like this:

CODE
function identify_member()
{
    if( isset( $_COOKIE['hash'] ) && isset( $_COOKIE['login_key'] ) )
    {
        $hash = addslashes( $_COOKIE['hash'] );
        $login_key = intval( $_COOKIE['login_key'] );

        if( mysql_num_rows( mysql_query( "SELECT * FROM users WHERE hash='$hash' AND lastlogin=$login_key" ) ) == 1 )
        {
            // get member info
        }
        else
        {
            // set guest
            return 'hi thar';
        }
    }
    else
    {
        // set guest        
        return 'i am a guest';
    }
}


The login key value is the time() value of user's last login, which changes every time they login.
This prevents people from hacking into cookies to log into other people's accounts if they know the hash, seeing they would need to know the exact time of their last login.
Even if they got in, the lastlogin time() is updated every time they login so they wouldn't be logged in permanently.
This method also prevents people to be logged in at 2 locations at once.
Futingkiller
the PhP script is great for me, but how do i create a table on MySQL?
i downloaded it from the internet, put it on a server. what next?
ICT Helpers
Great tutorial, thanks. I am new to PHP so it's a great help smile.gif
coldkill
You just need to run the script to create the table. Make sure you delete it afterwards though otherwise it may cause some problems.
changerhiphopmusic
The second one is going to kick pixels and code as well, um, I mean kick butt..lol.
I look 4wrd 2 it!!
Adam050
Hey

This looks like a very good member system. Ive just hade a very quick look through jue to i'm at school. I will test it out later and i hope your next part is good smile.gif
coldkill
Here is the next part of the system.

This will cover the login part of the system. It is the heart of any membership system. Without it there is no point in having a membership system.

This is a pretty simple script so it should be pretty easy to understand.

Let us continue our journey into membership systems!

---------------------------------------------------------------------

First we need a form so our users can put in their information and the script can check it.

I'm calling it login.htm

CODE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Your site.com - Login to access all kinds of goodies!</title>
</head>

<body>
<form name="form1" method="post" action="login.php">
  <table width="100%"  border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="7%">Username:</td>
      <td width="93%"><input name="username" type="text" id="username"></td>
    </tr>
    <tr>
      <td>Password:</td>
      <td><input name="password" type="password" id="password"></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Submit"></td>
    </tr>
  </table>
</form>
</body>
</html>


Now onto the magic. The comments tell the story.

CODE
<?php
/*
*    Session_start() This we use if we want to use sessions.
*    They are more secure than cookies but are only temporary
*/
session_start();
/*
*     Remeber our db file? Well we need to include it again
*/
include'db.php';

/*
*     Do some error checking.
*/
if( ! $_POST['username'] )
{
    /*
    *    If they didn't enter a username display an error and the form again
    */
    echo'<strong><font color=red>You didn\'t enter a username! Please enter one below!</font></strong>';
    include'login.htm';
    exit();
}
elseif( ! $_POST['password'] )
{
    /*
    *    If they didn't enter a password display an error and the form
    */    
    echo'<strong><font color=red>You didn\'t enter a password! Please enter one below!</font></strong>';
    include'login.htm';
    exit();
}

/*
*    OK so they entered all the stuff
*/

/*
*    Declare some standard vars
*/
$uname = $_POST['username'];

/*
*    This makes it difficult to perform an injection attack on your database
*/    
$username = mysql_real_escape_string( $uname );

/*
*    Remember we encrypted the password when we put it in the db?
*    Well we have to match the password because we can't decrypt it
*    The password doesn't need to be escaped since it is being encrypted
*/
$password = md5( $_POST['password'] );

$sql = mysql_query( "SELECT * FROM members WHERE username='$username' AND password='$password' LIMIT 1" );

/*
*    Did it find the account?
*/
$num = mysql_num_rows( $sql );
if( $num == 0 )
{
    /*
    *    If it found 0 rows then display an error, the form and exit the script
    */    
    echo'<strong><font color=red>That information is incorrect! Please try again</font></strong>';
    include'login.htm';
    exit();
}
else
{
    /*
    *    It found more than 0 rows (more than likely 1) so we can continue logging them in
    */
    
    /*
    *    First we need some data
    */
    $row = mysql_fetch_array( $sql );
    $user_level = $row['level'];
        $user_id = $row['id'];
}

/*
*       Roll out the red carpet and the welcoming comitee
*/
echo'Welcome to My Website '.$uname.'!';

/*
*    Remember we start our sessions? Lets define some now
*/
session_register( 'username' );

/*
*    To use sessions we use the $_SESSION superglobal we can also define sessions in this way
*/
$_SESSION['username'] = $username;

/*
*    This is repeated for the user's ID and user level which we use for security
*/
session_register( 'user_id' );
$_SESSION['user_id'] = $user_id;

session_register( 'user_level' );
$_SESSION['user_level'] = $user_level;

/*
*    So now they are logged in. That's it. Told ya it was simple;-)
*/

/*
*    Close down the database to save on resources
*/
mysql_close();

?>


Simple eh?

Well that's it for now i shall return soon and do some more.

Have fun,
Cold

::EDIT::
Edited a couple of things because they were incorrect.
Cold
coldkill
You may have noticed the function
CODE
session_start();

at the beginning of the page.

If you want to use sessions with the $_SESSION superglobal you will need to use that function AT THE BEGINNING of every page! Before any output is sent to the browser (which is echos, prints and HTML outside the <?PHP tags).

Have fun,
Cold
Martyn
Looks great! Im going to give it a try when I get home today, will let you know how it goes!!!
zetsumei
i get this error when logging in sad.gif

QUOTE
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in C:\Server\xampp\htdocs\admin\db.php on line 10
here is my db.php file

QUOTE
<?php

$user = "root";
$password = "*******";
$host = "localhost";
$db = "******";

$conn = mysql_connect( "$host","$user","$password" );

mysql_select_db("$db","$conn");

?>


i edited out the db name to keep my name safe until i can get a domain name
sp0173d_24
I really want to try this code
Delta
Will there be a continue of this good tutorial?........
Braunson
QUOTE(zetsumei @ Dec 19 2006, 06:00 AM) *
i get this error when logging in sad.gif

QUOTE
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in C:\Server\xampp\htdocs\admin\db.php on line 10
here is my db.php file

QUOTE
<?php

$user = "root";
$password = "*******";
$host = "localhost";
$db = "******";

$conn = mysql_connect( "$host","$user","$password" );

mysql_select_db("$db","$conn");

?>
i edited out the db name to keep my name safe until i can get a domain name




Try using this code.

CODE
<?php

$user = "root";
$password = "*******";
$host = "localhost";
$db = "******";

$conn = mysql_connect($host,$user,$password);
mysql_select_db($db,$conn) or die(mysql_error());

?>
smart-coder
Interesting Tutorial! I like it, I like the features that you've coded. Most members systems dont offer those. Unless they are pre built, like PHPBB. Anyways good job=)
spleen
nice tut
Kai Sellgren
Yep, nice tut.

I see some SQL and CSRF vulnerabilities. Some misunderstanding of terms also, eg. you are using 'encryption' in a situation when it is not about encrypting.
coldkill
Thanks for the praise on this. I'm surprised it's still up here after 3 years. To be honest I'd completely forgotten about it.

Bearing that in mind, coding practices have changed. I myself use OOP a lot now.

Technically, md5 is encryption. It is making the password unreadable without knowledge of what has happened to the string.

If you have problems such as "Incorrect Link Identifier specified on Line XX", that means that php was unable to connect to the MySQL database and has returned NULL.

If you have any problems, feel free to send me a PM.
choyaks
I would like to thank you sir for sharing this tutorial. It works for me! wohoo!!! even though I'm 3 years late.lol but thanks anyways It's a great tutorial for a beginner like me! smile.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.