Creating a user login and registration system. (3535 views)

In this tutorial we will teach you how to create a basic and simple user login and registration system for your website.


Hi and welcome to this new Combined-Minds.net PHP tutorial. In this tutorial I will teach you how to create your own login system. Quite simple, but worth reading.

First lets think of all the stuff we need to make a login system.

• SQL table with users
• Registration page
• Login page
• Page to see if the user is logged in

It's always easy to first think of what you truly need before programming. Planning your code saves hours of work.

Creating an SQL table

So, lets get started. This tutorial is quite basic, so I will show you how to create a new SQL table. You can make your table via systems like PHPmyAdmin or Navicat, but of course that's not cool. (at least I think it's not cool, I like to do everything myself)

When creating a table in SQL you start with "CREATE TABLE _tablename_". This is quite easy, just specify the name you want to use for your table. We'll use table name "login", so our first line will be "CREATE TABLE login".

The next step is to create the fields where the data needs to be stored in. Always think what fields are needed before creating the table. We'll do the same now:

• ID (user id, needs to be unique)
• username
• password (will be stored using a so-called "hash")
• email

The first field, the ID, will be an integer (an integer is a number). It needs to be unique for all users, so we'll use an AUTO_INCREMENT for that. This will make sure the new record in the table always has the highest possible number plus 1. (well it's a bit more complicated…)

The next field, username, will be stored as a variable char (VARCHAR). This simple mean it will be a string.

The third field will again be a variable char, but this time we'll save it a little different. While the other variable chars will be stored 100% like the user has given the server. The password field will use a MD5 hash. This means that the password will be converted to a series of characters that will make it impossible to read for the administrators. It would be kinda mean if we could just read everybody's password, wouldn't it?

The last field, the email field, will just be a variable char again.

Now to take this information to SQL. I will show you how I did it, and then explain it.

php
1
2
3
4
5
6
7
8

 
CREATE TABLE login (
ID mediumint(9) AUTO_INCREMENT PRIMARY KEY,
username varchar(100),
password varchar(40),
email varchar(100)
)
 
 


First of all, notice the "(" and ")" around the lines that cover the fields. That's to tell SQL that only these fields belong to the new table.

Second, you can see that all fields have their own line. You will understand most of it, except the number after "varchar" etc. Well, that indicated the maximum length of the field's content. So a username has a maximum of 100 characters in this example.

Also you probably don't understand the ID field for a bit. Lets take it apart and explain it.

Mediumint Is a field type, it can have a minimum number of -999999999 and a maximum number of 999999999. It would be useless to use a bigger type that can hold a higher number, because the ID will never reach this number and it will only take more space in MySQL.

AUTO_INCREMENT Tells the server that the new record has to be the highest number in the whole table.

PRIMARY KEY Means that ID has to be unique, it's now impossible to have a duplicate ID in the same table.

Well then, now run the SQL code, and create your table!

Registration page

Of course our members first have to register an account before they can login to our website, so lets make that.

Again lets think of what we need to build.

• HTML form
• PHP check if the user has filled in data
• Check the data, make sure there is not a duplicate username or email adres
• Store data in SQL table

Looks quite simple doesn't it? Lets begin.

First start of with your SQL connection, all connection details are different from server. So add it yourself.

If you don't know how to connect to a SQL server, take a look at this example:

php
1
2
3
4
5
6
7
8

 
<?php
 
$conn = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
mysql_select_db('database_that_contains_the_table', $conn); // Whoa, how long does a database name gets!
 
?>
 
 


I assume the HTML form isn't that hard. Just pay attention to the action and method types in the form element:

php
1
2
3
4
5
6
7
8
9
10
11
12
13

 
<form action="register.php?try=true" method="post">
 
Username: <input type="text" name="username"><br>
<br>
Password: <input type="password" name="password"><br>
<br>
Email: <input type="text" name="email"><br>
<br>
<input type="submit" value="register">
 
</form>
 
 


We'll need the action-page to contain "?try=true", this will tell our script later on that the user has triggered the switch! >

The method tells the server to send the data in a way the user can't see it directly (POST is send along with the headers/request). It would be quite nasty to see your password in GET variables, witch will be shown in the URL.

Now lets start with the PHP. The PHP will be in the same file as the HTML form (which has to be named register.php!). Make sure the PHP is on top of the form. To be sure I will show you my register.php later on the tutorial.

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

 
<?php
 
// is ?try=true in the url?
if (isset($_GET['try'])) {
 
	// Yes, the user has clicked on the submit button, let's check if he filled in all the fields
	if(empty($_POST['username']) OR 
   empty($_POST['password']) OR 
   empty($_POST['email']) ) {
 
	// At least one of the file is empty, display an error
	echo 'You haven\'t filled in all the fields. Please do it again.';
 
} else {
 
	// User has filled it all in!
 
	// GO ON WITH SCRIPT
 
}
 
}
 
?>
 


I hope you do understand this part, or else I'm up for a hell long night! Aah okay, I will explain some bits.

First you'll see the $_GET array. This stores all the GET data in the url. Eg: index.php?page=contact&sendEmail=true&bullcrap=nasty

Second is the empty() function which I use in the IF statement. Well, this function is TRUE when the variable in the function is 100% empty. So if one of the $_POST array fields are empty the IF function will execute the TRUE part of the code, which gives a nice error.

Well then, lets go on with checking the database if the username and email address are still free.

I will use the following query for that:

SELECT COUNT(id) FROM login WHERE username = 'a_username' OR email = 'mail@mail.com'

This counts all the rows that will have 'a_username' or has 'mail@mail.com' in their respectful fields.

In use it would look something like this:


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
43
44
45
46
47

 
<?php
 
// is ?try=true in the url?
if (isset($_GET['try'])) {
 
	// Yes, the user has clicked on the submit button, let's check if he filled in all the fields
	if(empty($_POST['username']) OR 
   empty($_POST['password']) OR 
   empty($_POST['email']) ) {
 
	// At least one of the file is empty, display an error
	echo 'You haven\'t filled in all the fields. Please do it again.';
 
} else {
 
	// User has filled it all in!
 
	// SQL save variables
	$username = mysql_real_escape_string($_POST['username']);
	$password = MD5($_POST['password']);
	$email = mysql_real_escape_string($_POST['email']);
 
		$query = mysql_query("SELECT COUNT(id) FROM login 
   WHERE username = '" . $username . "' 
   OR email = '" . $email . "' ") or die(mysql_error());
 
 
		list($count) = mysql_fetch_row($query);
 
		if($count == 0) {
 
			// Username and Email are free!
 
		} else {
 
			// Username or Email already taken
			echo 'Username or Email address already taken!';
 
		}
 
 
}
 
}
 
?>
 


Lets take a look at the list() function. What this function does, is saving the data directly in a variable. Normally we would get an array from it, but of course is much easier to store them in a clean variable at once.

I only select one field within the query, so I only need to list one, when selecting two fields, I will need a second variable in the list. (eg: list($count, $anotherVar)

If you don't know why I used "mysql_real_escape_string()" you have to read this tutorial: PHP Security: SQL Injection (Don't worry, it's simple!)
Now we can start with actually registering the users. Lets store them in the table!

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
43
44
45
46
47
48
49
50
51
52
53
54

 
<?php
 
// is ?try=true in the url?
if (isset($_GET['try'])) {
 
	// Yes, the user has clicked on the submit button, let's check if he filled in all the fields
	if(empty($_POST['username']) OR 
   empty($_POST['password']) OR 
   empty($_POST['email']) ) {
 
	// At least one of the file is empty, display an error
	echo 'You haven\'t filled in all the fields. Please do it again.';
 
} else {
 
	// User has filled it all in!
 
	// SQL save variables
	$username = mysql_real_escape_string($_POST['username']);
	$password = MD5($_POST['password']);
	$email = mysql_real_escape_string($_POST['email']);
 
		$query = mysql_query("SELECT COUNT(id) FROM login 
   WHERE username = '" . $username . "' 
   OR email = '" . $email . "' ") or die(mysql_error());
 
 
		list($count) = mysql_fetch_row($query);
 
		if($count == 0) {
 
			// Username and Email are free!
			mysql_query("INSERT INTO login
					(username, password, email)
					VALUES
					('" . $username . "', '" . $password . "', '" . $email . "')
					") or die(mysql_error());
 
			echo 'You are successfully registered!';
 
		} else {
 
			// Username or Email already taken
			echo 'Username or Email address already taken!';
 
		}
 
 
}
 
}
 
?>
 


I tested my version, and it seems to work just fine. Yours isn't working? Don't worry, you can download my files at the bottom of this website and check what you've done wrong.

Login page

Now lets go on with the actual login process. We'll use a technique called sessions. I assume most of you already know about sessions. But for the one's that don't, let me explain.

A session is a piece of information on the server that's only meant for you. To indicate which session belongs to which user on the website, they use session IDs. The session ID is stored on a cookie in the users browser. So the only thing you can see as a user is the session ID, which is (almost) useless. And the important data is stored on the server itself. This makes it a perfect technique for loggin' in.

So let's start with thinking of what we need on this page.

• HTML form
• Check if data is not empty
• Check if combination of username and password exists
• Create a session

That's pretty simple. It's almost the same as we did a few minutes ago with the registration page.

Let's start of with the HTML form. Again I'll assume it doesn't need any explanation.

php
1
2
3
4
5
6
7
8
9
10
11

 
<form action="login.php?try=true" method="post">
 
Username: <input type="text" name="username"><br>
<br>
Password: <input type="password" name="password"><br>
<br>
<input type="submit" value="Login!">
 
</form>
 
 


Aha simple enough!

Ok, now for the PHP stuff. Again don't forget to make your SQL connection!

I'll first write the code, and you just tell me what you don't understand.

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

 
<?php
 
// Check if user wants to login (GET info)
if(isset($_GET['try'])) {
 
	// That's nice, she wants to login. But lets check if she has filled in all information
	If(empty($_POST['username']) OR empty($_POST['password'])) {
 
		// She hasn't filled it all in!
		echo 'Please fill in all the required fields!';
 
	} else {
 
		// She filled it all in!
 
		// Oh, and maybe I should stop listening to Maroon 5 - _She_ will be loved
 
	}
 
}
 
?>
 
 


Hmm, I explained all that's to it on the registration page. I think we can start with searching for a combination of that password en username. But remember, we have to MD5 the password, and use mysql_real_escape_string() on the username.

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
43
44
45
46
47
48

 
<?php
 
// Check if user wants to login (GET info)
if(isset($_GET['try'])) {
 
	// That's nice, user wants to login. But lets check if user has filled in all information
	If(empty($_POST['username']) OR empty($_POST['password'])) {
 
		// User hasn't filled it all in!
		echo 'Please fill in all the required fields!';
 
	} else {
 
		// User filled it all in!
 
		// Make variables save with mysql_real_escape_string and md5
		$username = mysql_real_escape_string($_POST['username']);
		$password = md5($_POST['password']);
 
		// Search for a combination
		$query = mysql_query("SELECT id FROM login
					   WHERE username = '" . $username . "' 
					   AND password = '" . $password . "'
					  ") or die(mysql_error());
 
		// Save result
		list($user_id) = mysql_fetch_row($query);
 
		// If the user_id is empty no combination was found
		if(empty($user_id)) {
 
			echo 'No combination of username and password found.';
 
		} else {
 
			// the user_id variable doesn't seem to be empty, so a combination was found!
 
			// CREATE SESSION AND REDIRECT TO NEW PAGE
 
		}		
 
	}
 
}
 
?>
 
 


So, lets take a look at this code. We're using MySQL to search for a combination of our username and password. If one is found an id will be stored via the list() function. So we can just check if the user_id variable is empty or not.

Ok, were almost ready with the tutorial. The only thing we now need is to fix the Session, and to redirect to a new page that checks if the user is successfully logged in.

The first thing we need to do is start a session time. This means that PHP must check if a session is used, when you don't start a session time, you won't be able to use and make sessions!

Starting the session is very simple, just make sure that "session_start();" is on top of every PHP page that is using the session.

Now some more about sessions themselves. What is a session? Yes, Good question!... A session is an piece of the array "$_SESSION". So this variable contains all session information. To create a new session just create a new array key:

php
1
2
3
4
5
6
7
8
9
10
11

 
<?php
 
// Create new session
$_SESSION['somesessionname'] = 'session value';
 
// echoes "session value"
echo $_SESSION['somesessionname'];
 
?> 
 
 


One last thing is the redirect, we'll use the header() function for it. I won't bore you with the details of the function.

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
43
44
45
46
47
48
49
50
51
52
53
54
55

 
<?php
 
// Start the session (DON'T FORGET!!)
session_start();
 
// Check if user wants to login (GET info)
if(isset($_GET['try'])) {
 
	// That's nice, user wants to login. But lets check if user has filled in all information
	If(empty($_POST['username']) OR empty($_POST['password'])) {
 
		// User hasn't filled it all in!
		echo 'Please fill in all the required fields!';
 
	} else {
 
		// User filled it all in!
 
		// Make variables save with mysql_real_escape_string and md5
		$username = mysql_real_escape_string($_POST['username']);
		$password = md5($_POST['password']);
 
		// Search for a combination
		$query = mysql_query("SELECT id FROM login
					   WHERE username = '" . $username . "' 
					   AND password = '" . $password . "'
					  ") or die(mysql_error());
 
		// Save result
		list($user_id) = mysql_fetch_row($query);
 
		// If the user_id is empty no combination was found
		if(empty($user_id)) {
 
			echo 'No combination of username and password found.';
 
		} else {
 
			// the user_id variable doesn't seem to be empty, so a combination was found!
 
			// Create new session, store the user id
			$_SESSION['user_id'] = $user_id;
 
			// Redirect to userpanel.php
			header('location: userpanel.php');
 
		}		
 
	}
 
}
 
?>
 
 


Ok, now remember to paste the HTML form at the bottom of the page, and test it! It worked for me. Again, if yours isn't working, don't worry… Just download my version and see what you've done wrong.

Userpanel

Now the final stage of the tutorial! Let's see what we'll do on this page.

1. Check if the user is logged in
2. Get username via it's user ID

Well that shouldn't be too hard.

Ok lets get started, because we we'll not use a form in this page, we'll immediately start with PHP. First start the session with session_start(); and make a connection to the server.

Now lets check if the user is logged in or not! We can do this fairly simple by checking if the session exists!

php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

 
 
<?php
 
// Start session
session_start(); 
 
// Check if user is logged in
if(isset($_SESSION['user_id'])) {
 
	// User is logged in!
 
} else {
 
	// User not logged in
	echo 'Please login before opening the user panel.';
 
}
 
?>
 
 


This should be quite simple. Let's start with getting the username of this user from the database!

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

 
 
<?php
 
// Start session
session_start(); 
 
// Check if user is logged in
if(isset($_SESSION['user_id'])) {
 
	// User is logged in!
	$query = mysql_query("SELECT username FROM login
				   WHERE ID = " . $_SESSION['user_id'] . " LIMIT 1")
				   or die(mysql_error());
 
	list($username) = mysql_fetch_row($query);
 
	echo 'Hi '. $username . ', welcome to your profile!';
 
} else {
 
	// User not logged in
	echo 'Please login before opening the user panel.';
 
}
 
?>
 
 


This again should be very simple!

Well you've just written your own perfectly fine login and registration system for your website. For those who have trouble with following me, you can download my three files here. Of course you can also just open a topic at the forums.

Replies on Creating a user login and registration system.:
Jump to comment page: 1

 By man50 on Monday 31 March 2008 6:56

where is the download
link?????
i really need it




 By man50 on Monday 31 March 2008 17:03

i found it thx any ways tut




 By moslem on Friday 11 April 2008 2:03

yo good tut i have some qeustions furst of all can give my pages like how can see it or how can't see it? like the admin can go to the change or add script?

thanx,
moslem




 By Jim on Friday 11 April 2008 1:36

For admin style script, the most basic way is to make an extra session at login that tells you that you have admin rights.

And on admin page you check if that session exists.

It's not the most secure way (since this tutorial is not a super secure way of loggin in) but it should do just fine.




 By steve on Tuesday 22 April 2008 13:27

I enter correct username and password but its saids its wrong? what am I doing wrong?




 By Jim on Wednesday 23 April 2008 5:31

Some more information please, with just one line i can't help your problem

Please open a topic.




 By ORiOn on Thursday 08 May 2008 7:40

And for a logout page?
can you tell me how to do plz ?

I put:
session_cache_expire()
and:
session_destroy()

but it does not work




 By Jim on Thursday 15 May 2008 6:45

Are you sure you first start the session before you try to delete it?




 By newtoid on Wednesday 11 June 2008 23:42

this is very good

how about a forgot password/edit details bit?




 By Jim on Monday 16 June 2008 3:35

Hmmm, not to be unrespectful, but that would be a bit to hard for beginners. If you do want to make it, try looking up some information about the SQL UPDATE command. That can update values in the table (eg passwords and profile information).




 By darkmatter5 on Friday 27 June 2008 13:21

Great tutorial, it all worked great and is really straight forward and clear., but when I use the login button and it creates the session and forwards you to the userpanel.php file I get the result of, "Please login before opening the user panel!" My code matches your code in the tutorial. I've put 'echo $user_id;' in login.php in the last else and commented out '$_SESSION['user_id'] = $user_id;' and 'header('location: userpanel.php');' and it does outputs the user_id from the table of the user entered in the form. But as far as I can tell the last 2 lines of the else statement in login.php aren't actually passing the session correctly to userpanel.php. Any help is appreciated!!




 By Jim on Friday 11 July 2008 18:03

Please make a new topic with your code, that way it's easy to spot any mistakes




 By Linnabery27 on Tuesday 05 August 2008 22:19

@darkmatter5

I had the exact same problem as you, and after hours of futile attempts at searching the internet for an answer (and racking my brain over and over trying to find a tiny syntax error somewhere) I found a solution. I had to login to my host's script configuration and change the version of php from PHP 4 to PHP 5. Also inside the php.ini file, there is a setting for auto_start_session. It was set to false for me. I edited that setting to say true, an Voila! Much to my pleasure my login worked and everything fell into place.


FYI -- there are a few other nice settings to tweak as well, including the displaying of all error messages. This comes in super handy when you are a beginning PHPer like myself. It takes all the stress out of trying to comb through all those lines of code just to find the misplaced semicolon.

hope this helps you out a little bit!




 By tuhkur on Monday 11 August 2008 1:47

Table 'np10161_table.login' doesn't exist what is this cant understand, i get this when pressing register button :S




 By tuhkur on Monday 11 August 2008 2:02

nvm i got it i was stupid, great tutorial keep it going




 By max on Monday 11 August 2008 20:09

Can someone tell me where to find the download link for this tutorial pls ?




 By max on Monday 11 August 2008 20:24

got it ! Thx jim !



Jump to comment page: 1
You are not logged in. Please login or register an account, it just takes 30 seconds.


©Copyrights Combined Minds. All rights reserved 2006 - 2008 : Disclaimer
Realized by www.Minna-Media.com