Jump to content
xisto Community
Sign in to follow this  
Brian010011405241556

Site Login How to make a login system

Recommended Posts

Heres an easy way to make a registration/login system for your site. 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.

Code:
1

2
CREATE TABLE login (
3
ID mediumint(9) AUTO_INCREMENT PRIMARY KEY,
4
username varchar(100),
5
password varchar(40),
6
email varchar(100)
7
)
8




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:

Code:
1

2
<?php
3

4
$conn = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
5
mysql_select_db('database_that_contains_the_table', $conn); // Whoa, how long does a database name gets!
6

7
?>
8




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

Code:
1

2
<form action="register.php?try=true" method="post">
3

4
Username: <input type="text" name="username"><br>
5
<br>
6
Password: <input type="password" name="password"><br>
7
<br>
8
Email: <input type="text" name="email"><br>
9
<br>
10
<input type="submit" value="register">
11

12
</form>
13




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.

Code:
1

2
<?php
3

4
// is ?try=true in the url?
5
if (isset($_GET['try'])) {
6

7
// Yes, the user has clicked on the submit button, let's check if he filled in all the fields
8
if(empty($_POST['username']) OR
9
empty($_POST['password']) OR
10
empty($_POST['email']) ) {
11

12
// At least one of the file is empty, display an error
13
echo 'You haven\'t filled in all the fields. Please do it again.';
14

15
} else {
16

17
// User has filled it all in!
18

19
// GO ON WITH SCRIPT
20

21
}
22

23
}
24

25
?>



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:


Code:
1

2
<?php
3

4
// is ?try=true in the url?
5
if (isset($_GET['try'])) {
6

7
// Yes, the user has clicked on the submit button, let's check if he filled in all the fields
8
if(empty($_POST['username']) OR
9
empty($_POST['password']) OR
10
empty($_POST['email']) ) {
11

12
// At least one of the file is empty, display an error
13
echo 'You haven\'t filled in all the fields. Please do it again.';
14

15
} else {
16

17
// User has filled it all in!
18

19
// SQL save variables
20
$username = addslashes($_POST['username']);
21
$password = MD5($_POST['password']);
22
$email = addslashes($_POST['email']);
23

24
$query = mysql_query("SELECT COUNT(id) FROM login
25
WHERE username = '" . $username . "'
26
OR email = '" . $email . "' ") or die(mysql_error());
27

28

29
list($count) = mysql_fetch_row($query);
30

31
if($count == 0) {
32

33
// Username and Email are free!
34

35
} else {
36

37
// Username or Email already taken
38
echo 'Username or Email address already taken!';
39

40
}
41

42

43
}
44

45
}
46

47
?>



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 "addslashes()" 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!

Code:
1

2
<?php
3

4
// is ?try=true in the url?
5
if (isset($_GET['try'])) {
6

7
// Yes, the user has clicked on the submit button, let's check if he filled in all the fields
8
if(empty($_POST['username']) OR
9
empty($_POST['password']) OR
10
empty($_POST['email']) ) {
11

12
// At least one of the file is empty, display an error
13
echo 'You haven\'t filled in all the fields. Please do it again.';
14

15
} else {
16

17
// User has filled it all in!
18

19
// SQL save variables
20
$username = addslashes($_POST['username']);
21
$password = MD5($_POST['password']);
22
$email = addslashes($_POST['email']);
23

24
$query = mysql_query("SELECT COUNT(id) FROM login
25
WHERE username = '" . $username . "'
26
OR email = '" . $email . "' ") or die(mysql_error());
27

28

29
list($count) = mysql_fetch_row($query);
30

31
if($count == 0) {
32

33
// Username and Email are free!
34
mysql_query("INSERT INTO login
35
(username, password, email)
36
VALUES
37
('" . $username . "', '" . $password . "', '" . $email . "')
38
") or die(mysql_error());
39

40
echo 'You are successfully registered!';
41

42
} else {
43

44
// Username or Email already taken
45
echo 'Username or Email address already taken!';
46

47
}
48

49

50
}
51

52
}
53

54
?>



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.

Code:
1

2
<form action="login.php?try=true" method="post">
3

4
Username: <input type="text" name="username"><br>
5
<br>
6
Password: <input type="password" name="password"><br>
7
<br>
8
<input type="submit" value="Login!">
9

10
</form>
11




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.

Code:
1

2
<?php
3

4
// Check if user wants to login (GET info)
5
if(isset($_GET['try'])) {
6

7
// That's nice, she wants to login. But lets check if she has filled in all information
8
If(empty($_POST['username']) OR empty($_POST['password'])) {
9

10
// She hasn't filled it all in!
11
echo 'Please fill in all the required fields!';
12

13
} else {
14

15
// She filled it all in!
16

17
// Oh, and maybe I should stop listening to Maroon 5 - _She_ will be loved
18

19
}
20

21
}
22

23
?>
24




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 addslashes() on the username.

Code:
1

2
<?php
3

4
// Check if user wants to login (GET info)
5
if(isset($_GET['try'])) {
6

7
// That's nice, user wants to login. But lets check if user has filled in all information
8
If(empty($_POST['username']) OR empty($_POST['password'])) {
9

10
// User hasn't filled it all in!
11
echo 'Please fill in all the required fields!';
12

13
} else {
14

15
// User filled it all in!
16

17
// Make variables save with addslashes and md5
18
$username = addslashes($_POST['username']);
19
$password = md5($_POST['password']);
20

21
// Search for a combination
22
$query = mysql_query("SELECT id FROM login
23
WHERE username = '" . $username . "'
24
AND password = '" . $password . "'
25
") or die(mysql_error());
26

27
// Save result
28
list($user_id) = mysql_fetch_row($query);
29

30
// If the user_id is empty no combination was found
31
if(empty($user_id)) {
32

33
echo 'No combination of username and password found.';
34

35
} else {
36

37
// the user_id variable doesn't seem to be empty, so a combination was found!
38

39
// CREATE SESSION AND REDIRECT TO NEW PAGE
40

41
}
42

43
}
44

45
}
46

47
?>
48




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:

Code:
1

2
<?php
3

4
// Create new session
5
$_SESSION['somesessionname'] = 'session value';
6

7
// echoes "session value"
8
echo $_SESSION['somesessionname'];
9

10
?>
11




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.

Code:
1

2
<?php
3

4
// Start the session (DON'T FORGET!!)
5
session_start();
6

7
// Check if user wants to login (GET info)
8
if(isset($_GET['try'])) {
9

10
// That's nice, user wants to login. But lets check if user has filled in all information
11
If(empty($_POST['username']) OR empty($_POST['password'])) {
12

13
// User hasn't filled it all in!
14
echo 'Please fill in all the required fields!';
15

16
} else {
17

18
// User filled it all in!
19

20
// Make variables save with addslashes and md5
21
$username = addslashes($_POST['username']);
22
$password = md5($_POST['password']);
23

24
// Search for a combination
25
$query = mysql_query("SELECT id FROM login
26
WHERE username = '" . $username . "'
27
AND password = '" . $password . "'
28
") or die(mysql_error());
29

30
// Save result
31
list($user_id) = mysql_fetch_row($query);
32

33
// If the user_id is empty no combination was found
34
if(empty($user_id)) {
35

36
echo 'No combination of username and password found.';
37

38
} else {
39

40
// the user_id variable doesn't seem to be empty, so a combination was found!
41

42
// Create new session, store the user id
43
$_SESSION['user_id'] = $user_id;
44

45
// Redirect to userpanel.php
46
header('location: userpanel.php');
47

48
}
49

50
}
51

52
}
53

54
?>
55




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!

Code:
1

2
<?php
3

4
// Start session
5
session_start();
6

7
// Check if user is logged in
8
if(isset($_SESSION['user_id'])) {
9

10
// User is logged in!
11

12
} else {
13

14
// User not logged in
15
echo 'Please login before opening the user panel.';
16

17
}
18

19
?>
20




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

Code:
1

2
<?php
3

4
// Start session
5
session_start();
6

7
// Check if user is logged in
8
if(isset($_SESSION['user_id'])) {
9

10
// User is logged in!
11
$query = mysql_query("SELECT username FROM login
12
WHERE ID = " . $_SESSION['user_id'] . " LIMIT 1")
13
or die(mysql_error());
14

15
list($username) = mysql_fetch_row($query);
16

17
echo 'Hi '. $username . ', welcome to your profile!';
18

19
} else {
20

21
// User not logged in
22
echo 'Please login before opening the user panel.';
23

24
}
25

26
?>
27




And there you have it. If you need any help with this stuff msg me on here. Hope that help you.


Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.