Jump to content


Photo
- - - - -

Membership System


  • Please log in to reply
23 replies to this topic

#1 coldkill

coldkill

    Young Padawan

  • Members
  • Pip
  • 11 posts
  • Gender:Male
  • Location:Devon, United Kingdom

Posted 30 December 2005 - 09:38 PM

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
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:
<?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.
<?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...
<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...

<?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<[email protected]>\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

Edited by coldkill, 19 June 2006 - 05:37 PM.


#2 Nike

Nike

    Young Padawan

  • Members
  • Pip
  • 204 posts
  • Location:Ohio
  • Interests:Controlling the human and and duck race.

Posted 02 January 2006 - 02:48 AM

This tutorial is almost like Techtuts. But this is a bit more informative.

#3 coldkill

coldkill

    Young Padawan

  • Members
  • Pip
  • 11 posts
  • Gender:Male
  • Location:Devon, United Kingdom

Posted 03 January 2006 - 06:36 PM

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 ;)

#4 Indigo

Indigo

    Official Alien

  • Members
  • PipPipPip
  • 617 posts
  • Gender:Male
  • Location:Trondheim, Norway
  • Interests:Computing in general, especially design and programming of all kinds.

Posted 09 January 2006 - 07:47 AM

About when will the next part be up, and what will it contain?

#5 coldkill

coldkill

    Young Padawan

  • Members
  • Pip
  • 11 posts
  • Gender:Male
  • Location:Devon, United Kingdom

Posted 12 January 2006 - 11:47 AM

It will contain the login and lost password part of the system. It will be up soon.

#6 fRe3zE

fRe3zE

    Young Padawan

  • Members
  • Pip
  • 1 posts

Posted 03 April 2006 - 04:48 AM

err.. were is the rest?

#7 Ruben K

Ruben K

    Cliff

  • Twodded Staff
  • PipPip
  • 438 posts

Posted 07 April 2006 - 04:55 AM

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:

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.

Edited by Cliff, 07 April 2006 - 04:56 AM.


#8 Futingkiller

Futingkiller

    Young Padawan

  • Members
  • Pip
  • 110 posts

Posted 10 April 2006 - 04:51 PM

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?

#9 ICT Helpers

ICT Helpers

    Young Padawan

  • Members
  • Pip
  • 56 posts
  • Location:England

Posted 14 April 2006 - 06:11 AM

Great tutorial, thanks. I am new to PHP so it's a great help :)

#10 coldkill

coldkill

    Young Padawan

  • Members
  • Pip
  • 11 posts
  • Gender:Male
  • Location:Devon, United Kingdom

Posted 26 April 2006 - 02:58 PM

You just need to run the script to create the table. Make sure you delete it afterwards though otherwise it may cause some problems.

Edited by coldkill, 26 April 2006 - 02:59 PM.


#11 changerhiphopmusic

changerhiphopmusic

    Young Padawan

  • Members
  • Pip
  • 51 posts

Posted 05 May 2006 - 04:44 PM

The second one is going to kick pixels and code as well, um, I mean kick butt..lol.
I look 4wrd 2 it!!

#12 Adam050

Adam050

    Young Padawan

  • Members
  • Pip
  • 2 posts

Posted 05 June 2006 - 08:13 AM

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 :)

#13 coldkill

coldkill

    Young Padawan

  • Members
  • Pip
  • 11 posts
  • Gender:Male
  • Location:Devon, United Kingdom

Posted 19 June 2006 - 05:41 PM

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

<!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.

<?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

Edited by coldkill, 09 September 2006 - 05:32 PM.


#14 coldkill

coldkill

    Young Padawan

  • Members
  • Pip
  • 11 posts
  • Gender:Male
  • Location:Devon, United Kingdom

Posted 20 June 2006 - 05:19 AM

You may have noticed the function
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

#15 Martyn

Martyn

    Young Padawan

  • Members
  • Pip
  • 4 posts
  • Location:Horsham, England
  • Interests:Computers, Gaming, and Sports (Football and Cricket). Also my girlfriend of course!

Posted 03 October 2006 - 06:29 AM

Looks great! Im going to give it a try when I get home today, will let you know how it goes!!!

#16 zetsumei

zetsumei

    Young Padawan

  • Publishing Betazoids
  • Pip
  • 269 posts
  • Gender:Male
  • Location:127.0.0.1

Posted 19 December 2006 - 01:00 AM

i get this error when logging in -_-

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

<?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

Edited by zetsumei, 19 December 2006 - 01:02 AM.


#17 sp0173d_24

sp0173d_24

    Young Padawan

  • Members
  • Pip
  • 216 posts
  • Gender:Male
  • Location:United Arab Emirates
  • Interests:Web Designing, Learning Multimedia,Programming

Posted 19 December 2006 - 02:35 AM

I really want to try this code

#18 Delta

Delta

    Young Padawan

  • Members
  • Pip
  • 11 posts

Posted 31 December 2006 - 09:47 AM

Will there be a continue of this good tutorial?........

#19 Braunson

Braunson

    Young Padawan

  • Members
  • Pip
  • 237 posts
  • Gender:Male
  • Location:Ontario, Canada

Posted 23 January 2007 - 05:04 PM

i get this error when logging in ;)

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

<?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.

<?php

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

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

?>


#20 smart-coder

smart-coder

    Young Padawan

  • Members
  • Pip
  • 16 posts

Posted 29 January 2007 - 04:50 PM

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=)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users