You are on page 1of 31

1 J A N U A R Y , 2 0 1 9

বাংলা সং রণ

MENU

PHP Professional এবং Zend Certified PHP Engineer (ZCPE ) Course এ সীিমত সংখ ক
আসন বািক আেছ। আ হীেদরেক অিতস র মাসুদ আলম স ার এর সােথ যাগােযাগ করার জন অনুেরাধ করা যাে ।
স ার এর মাবাইল ন র : ০১৭২২ ৮১ ৭৫ ৯১

P O S T1 E2 D J U
B
O M
Y
LN A
Y ,S U 2D 0 1A 2 L A M

Build a Full-Featured Login


System with PHP

In this tutorial I will be showing you how to make a simple login system consisting of a login page,
register page, forgotten password page, email activation, logout page and finally a users online page. I
made this tutorial to mainly target new-to-PHP developers, due to the fact when I started I noticed the
lack in quantity of basic login systems. Therefore, I decided to make one myself giving high quality
advice on how to make your first login system with a users online script!

1. Making a basic stylesheet


We are going to create a very basic CSS stylesheet just to add a little bit of design and tidy up the way
this login system looks. So too start off with open your text editor and we can begin making our
styelsheet.

1 body {
2
3 font-family: arial;
4
5 font-size: 10pt;
6
7 }
8
9 table {
10
11 font-size: 10pt;
12
13 margin: 0 auto;
14
15 }
16
17 #border {
18
19 border: 2px solid #999;
20
21 background: #CCC;
22
23 padding: 15px;
24
25 margin: 0 auto;
26
27 width: 300px;
28
29 }

Save this file as style.css so we can link back to it whenever we need to. There we have our simple
stylesheet! Now we can begin making our pages without having to worry too much about making them
look reasonably good.

2. Creating the Login Page


Okay so we have a stylesheet defined, now it’s time to get things displaying on our pages. Open a new
file in your text editor, this is going to be our login.php page!

1 <html>
2 <head>
3 <title>Login with Users Online Tutorial</title>
4 <link rel="stylesheet" type="text/css" href="style.css" />
5 </head>
6 <body>
7 <form action="login.php" method="post">
8 <div id="border">
9 <table cellpadding="2" cellspacing="0" border="0">
10 <tr>
11 <td>Username:</td>
12 <td><input type="text" name="username" /></td>
13 </tr>
14 <tr>
15 <td>Password:</td>
16 <td><input type="password" name="password" /></td>
17 </tr>
<tr>
18 <tr>
19 <td colspan="2" align="center"><input type="submit" name="submit" value="Login" /></td>
20 </tr>
21 <tr>
22 <td align="center" colspan="2"><a href="register.php">Register</a> | <a
href="forgot.php">Forgot Pass</a></td>
23 </tr>
24 </table>
25 </div>
26 </form>
27 </body>
28 </html>

Out Login Page Look like:

At the moment you will notice that it doesn’t work. This is because we have not told the page what to do
if the form is submitted.

Planning

Now let’s do some planning before we dive into the PHP. We need to ask ourselves “What is the page
going to be checking when the form is submitted?”. For the login page here is a list of what we are going
to be checking –

• That both the username and password boxes have been filled in

• That the username supplied exists in our database

• That if the username exists in our database, the password matches the one for the username

• Finally, that the user has activated their account

If the PHP can answer yes to all four of those points, then log the user in. Now in those four points you
will notice there was a database mentioned. We are going to be using a MySQL database to store all of
the information about each of our users. So before we get started on out PHP we need to make this
database. At this point a bit more planning is needed. We need to decide what information we need to
store about the users, what types of data are we storing, do we need a default value etc etc. Here is my
plan below –

• We need to store a username for the user which will be a varchar

• We need a password to which will also be a varchar

• We will need an email for our email activation function this can be varchar too
• A field telling is if the account has been activated or not, this will be an integer

• A field giving information about whether the user is online or not, this will be an integer

• Finally, a field giving us a time the user registered, this is also an integer

Building the Database

Now from this we can see exactly how to build our table in our database. First create a database called
loginTut. Then in this database we want to run the SQL I have provided below –

1 CREATE TABLE `users` (


2
3 `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
4 `username` VARCHAR( 32 ) NOT NULL ,
5 `password` VARCHAR( 32 ) NOT NULL ,
6 `online` INT( 20 ) NOT NULL ,
7 `email` VARCHAR( 100 ) NOT NULL ,
8 `active` INT( 1 ) NOT NULL ,
9 `rtime` INT( 20 ) NOT NULL
10
11 ) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Now we have a table to store all the information we need about our users, let’s add a user for testing
purposes. To do this run the SQL provided below –

1 INSERT INTO users( id, username,


2 PASSWORD , online, email, active, rtime )
3 VALUES ( 1, 'testing', 'testing', 0, 'fake@noemail.co.uk', 0, 0 )

So we now have one user with the username testing, the password testing and email
fake@noemail.co.uk. Now we can get to the PHP and make out login form work!

Adding the PHP

First things first we need to think about security and how secure is this login form going to be. To help
prevent SQL Injection which is a very common form of database hacking we are going to make a
function that will protect all strings stored in the database. This we will put in an external file called
functions.php. Here is the source –

1 <?php
2 function protect($string){
3 $string = trim(strip_tags(addslashes($string)));
4 return $string;
5 }
6 ?>

Now Create a Database Configuration File called config.php

1 <?php
2 $con = mysqli_connect('localhost', 'root', '','content');
3 ?>
This function will trim our string (cut off any white space at the beginning or end of the string), strip tags
(remove all html and PHP tags in the string), and then add slashes to the string escaping speech marks
(’) and quotation marks (“).

Back to login.php

Now we have a place to store and check user information from, a function to protect strings being
passed to the database, and a nice looking layout for our login page! Below you can see the commented
code for our login.php file with the newly added PHP-

1 <?php
2
3 //allow sessions to be passed so we can see if the user is logged in
4
5 session_start();
6
7 ob_start();
8
9 //connect to the database so we can check, edit, or insert data to our users table
10
11 include('config.php');
12
13 //include out functions file giving us access to the protect() function made earlier
14
15 include "functions.php";
16
17 ?>
18
19 <html>
20
21 <head>
22
23 <title>Login with Users Online Tutorial</title>
24
25 <link rel="stylesheet" type="text/css" href="style.css" />
26
27 </head>
28
29 <body>
30
31 <?php
32
33 //If the user has submitted the form
34
35 if($_POST['submit']){
36
37 //protect the posted value then store them to variables
38
39 $username = protect($_POST['username']);
40
41 $password = protect($_POST['password']);
42
43 //Check if the username or password boxes were not filled in
44
45 if(!$username || !$password){
46
47 //if not display an error message
48
49 echo "<center>You need to fill in a <b>Username</b> and a <b>Password</b>!</center>";
50
51 }else{
52
//if the were continue checking
53 //if the were continue checking
54
55 //select all rows from the table where the username matches the one entered by the user
56
57 $res = mysqli_query($con,"SELECT * FROM `users` WHERE `username` = '".$username."'");
58
59 $num = mysqli_num_rows($res);
60
61 //check if there was not a match
62
63 if($num == 0){
64
65 //if not display an error message
66
67 echo "<center>The <b>Username</b> you supplied does not exist!</center>";
68
69 }else{
70
71 //if there was a match continue checking
72
73 //select all rows where the username and password match the ones submitted by the user
74
75 $res = mysqli_query($con,"SELECT * FROM `users` WHERE `username` = '".$username."'
AND `password` = '". md5($password)."'");
76
77 $num = mysqli_num_rows($res);
78
79 //check if there was not a match
80
81 if($num == 0){
82
83 //if not display error message
84
85 echo "<center>The <b>Password</b> you supplied does not match the one for that username!
</center>";
86
87 }else{
88
89 //if there was continue checking
90
91 //split all fields fom the correct row into an associative array
92
93 $row = mysqli_fetch_assoc($res);
94
95 //check to see if the user has not activated their account yet
96
97 if($row['active'] != 1){
98
99 //if not display error message
100
101 echo "<center>You have not yet <b>Activated</b> your account!</center>";
102
103 }else{
104
105 //if they have log them in
106
107 //set the login session storing there id - we use this to see if they are logged in or not
108
109 $_SESSION['uid'] = $row['id'];
110
111 //show message
112
113 echo "<center>You have successfully logged in!</center>";
114
115 //update the online field to 50 seconds into the future
116
117 $time = date('U')+50;
118
119 mysqli_query($con,"UPDATE `users` SET `online` = '" .$time."' WHERE `id` =
'".$_SESSION['uid']."'");
120
121 //redirect them to the usersonline page
122
123 header('Location: usersOnline.php');
124
125 }
126
127 }
128
129 }
130
131 }
132
133 }
134
135 ?>
136
137 <form action="login.php" method="post">
138
139 <div id="border">
140
141 <table cellpadding="2" cellspacing="0" border="0">
142
143 <tr>
144
145 <td>Username:</td>
146
147 <td><input type="text" name="username" /></td>
148
149 </tr>
150
151 <tr>
152
153 <td>Password:</td>
154
155 <td><input type="password" name="password" /></td>
156
157 </tr>
158
159 <tr>
160
161 <td colspan="2" align="center"><input type="submit" name="submit" value="Login" /></td>
162
163 </tr>
164
165 <tr>
166
167 <td align="center" colspan="2"><a href="register.php">Register</a> | <a
href="forgot.php">Forgot Pass</a></td>
168
169 </tr>
170
171 </table>
172
173 </div>
174
175 </form>
176
177 </body>
178
179 </html>
180
181 <?php
182
ob_end_flush();
183 ob_end_flush();

184
185 ?>

Most of this is explained by the commenting but one part I didn’t explain is the online field. When you
successfully login, we updated the online field to 50 seconds ahead of now. The date(‘U’) function gives
us a the amount of seconds since January 1 1970 00:00:00 GMT (Unix epoch). This means that
date(‘U’) will never get smaller, the value will always increase. If we set the online field to 50 seconds
ahead of now then when the Users Online page is loaded we can check to find all the users where the
online value is more than the time when the page is loaded, if this is the case then display each of their
names.

Now feel free to test your login page. Make sure that all the checks are performed correctly and that
once successfully logged in, you get redirected to the non existing users online page. You can also
check to see if it has successfully updated the online field by checking your users table!

3. Creating the Register Page


What good is a login page without a register page? Not much at all so I think that will be the next step
for us to take. Creating the register page is going to be very similar to creating our login page. We need
to do some basic check to see if the username wanted is already taken, but there’s nothing new
happening there. Below you can see the commented register page code –

1 <?php
2
3 //allow sessions to be passed so we can see if the user is logged in
4
5 session_start();
6
7 //connect to the database so we can check, edit, or insert data to our users table
8
9 include('config.php');
10
11 //include out functions file giving us access to the protect() function
12
13 include "functions.php";
14
15 ?>
16
17 <html>
18
19 <head>
20
21 <title>Login with Users Online Tutorial</title>
22
23 <link rel="stylesheet" type="text/css" href="style.css" />
24
25 </head>
26
27 <body>
28
29 <?php
30
31 //Check to see if the form has been submitted
32
33 if(isset($_POST['submit'])){
34

35 //protect and then add the posted data to variables


36
37 $username = protect($_POST['username']);
38
39 $password = protect($_POST['password']);
40
41 $passconf = protect($_POST['passconf']);
42
43 $email = protect($_POST['email']);
44
45 //check to see if any of the boxes were not filled in
46
47 if(!$username || !$password || !$passconf || !$email){
48
49 //if any weren't display the error message
50
51 echo "<center>You need to fill in all of the required filds!</center>";
52
53 }else{
54
55 //if all were filled in continue checking
56
57 //Check if the wanted username is more than 32 or less than 3 charcters long
58
59 if(strlen($username) > 32 || strlen($username) < 3){
60
61 //if it is display error message
62
63 echo "<center>Your <b>Username</b> must be between 3 and 32 characters long!
</center>";
64
65 }else{
66
67 //if not continue checking
68
69 //select all the rows from out users table where the posted username matches the username
stored
70
71 $res = mysqli_query($con,"SELECT * FROM `users` WHERE `username` = '".$username."'");
72
73 $num = mysqli_num_rows($res);
74
75 //check if theres a match
76
77 if($num == 1){
78
79 //if yes the username is taken so display error message
80
81 echo "<center>The <b>Username</b> you have chosen is already taken!</center>";
82
83 }else{
84
85 //otherwise continue checking
86
87 //check if the password is less than 5 or more than 32 characters long
88
89 if(strlen($password) < 5 || strlen($password) > 32){
90
91 //if it is display error message
92
93 echo "<center>Your <b>Password</b> must be between 5 and 32 characters long!</center>" ;
94
95 }else{
96
97 //else continue checking
98
99 //check if the password and confirm password match
100
101 if($password != $passconf){
102
103 //if not display error message
104
105 echo "<center>The <b>Password</b> you supplied did not math the confirmation password!
</center>";
106
107 }else{
108
109 //otherwise continue checking
110
111 //Set the format we want to check out email address against
112
113 $checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
114
115 //check if the formats match
116
117 if(!preg_match($checkemail, $email)){
118
119 //if not display error message
120
121 echo "<center>The <b>E-mail</b> is not valid, must be name@server.tld!</center>";
122
123 }else{
124
125 //if they do, continue checking
126
127 //select all rows from our users table where the emails match
128
129 $res1 = mysqli_query($con,"SELECT * FROM `users` WHERE `email` = '".$email."'");
130
131 $num1 = mysqli_num_rows($res1);
132
133 //if the number of matchs is 1
134
135 if($num1 == 1){
136
137 //the email address supplied is taken so display error message
138
139 echo "<center>The <b>E-mail</b> address you supplied is already taken</center>";
140
141 }else{
142
143 //finally, otherwise register there account
144
145 //time of register (unix)
146
147 $registerTime = date('U');
148
149 //make a code for our activation key
150
151 $code = md5($username).$registerTime;
152
153 //insert the row into the database
154
155 $res2 = mysqli_query($con,"INSERT INTO `users` (`username`, `password`, `email`, `rtime`)
VALUES('".$username."','".md5($password)."','".$email."','".$registerTime."')");
156
157 //send the email with an email containing the activation link to the supplied email address
158
159 mail($email, $INFO['chatName'].' registration confirmation', "Thank you for registering to us
".$username.",\n\nHere is your activation link. If the link doesn't work copy and paste it into
your browser address bar.\n\nhttp://www.yourwebsitehere.co.uk/activate.php?code=".$code,
'From: noreply@youwebsitehere.co.uk');
'From: noreply@youwebsitehere.co.uk');
160
161 //display the success message
162
163 echo "<center>You have successfully registered, please visit you inbox to activate your
account!</center>";
164
165 }
166
167 }
168
169 }
170
171 }
172
173 }
174
175 }
176
177 }
178
179 }
180
181 ?>
182
183 <div id="border">
184
185 <form action="register.php" method="post">
186
187 <table cellpadding="2" cellspacing="0" border="0">
188
189 <tr>
190
191 <td>Username: </td>
192
193 <td><input type="text" name="username" /></td>
194
195 </tr>
196
197 <tr>
198
199 <td>Password: </td>
200
201 <td><input type="password" name="password" /></td>
202
203 </tr>
204
205 <tr>
206
207 <td>Confirm Password: </td>
208
209 <td><input type="password" name="passconf" /></td>
210
211 </tr>
212
213 <tr>
214
215 <td>Email: </td>
216
217 <td><input type="text" name="email" size="25"/></td>
218
219 </tr>
220
221 <tr>
222
223 <td colspan="2" align="center"><input type="submit" name="submit" value="Register" /></td>
224
225 </tr>
226

227 <tr>
228
229 <td colspan="2" align="center"><a href="login.php">Login</a> | <a href="forgot.php">Forgot
Pass</a></a></td>
230
231 </tr>
232
233 </table>
234
235 </form>
236
237 </div>
238
239 </body>
240
241 </html>

Now Our Registration Page Look like:

New Functions

This file contains some new things you may not be familiar with, therefore I will go over everything.
Firstly, the strlen() function, this returns the number of characters in a string allowing us to check how
long strings are. Then the preg_match() function, this checks to see if the formatting of a string matches
the formatting you specify (in this case being an email format). Finally the mail() function, this sends an
email from the server to any email of your choice, containing anything you want. You should save this
file as register.php

Now you can test you register page, you can see when you enter your correct email address you will
receive an email with an activation link contained inside. You can also see that a row containing the data
filled into the form is entered into the users table. The value of active is 0 showing that this account has
not yet been activated!

4. Activate Your Account Page


This is only a small page with very little code required, but it’s still very important and plays a huge role
in a secure login system. The source for this page is shown below – activate.php
1 <?php
2
3 //allow sessions to be passed so we can see if the user is logged in
4
5 session_start();
6
7 //connect to the database so we can check, edit, or insert data to our users table
8
9 include('config.php');
10 //include out functions file giving us access to the protect() function made earlier
11
12 include "functions.php";
13
14 ?>
15
16 <html>
17
18 <head>
19
20 <title>Login with Users Online Tutorial</title>
21
22 <link rel="stylesheet" type="text/css" href="style.css" />
23
24 </head>
25
26 <body>
27
28 <?php
29
30 echo md5('other');
31
32 //get the code that is being checked and protect it before assigning it to a variable
33
34 $code = protect($_GET['code']);
35
36 //check if there was no code found
37
38 if(!$code){
39
40 //if not display error message
41
42 echo "<center>Unfortunatly there was an error there!</center>" ;
43
44 }else{
45
46 //other wise continue the check
47
48 //select all the rows where the accounts are not active
49
50 $res = mysqli_query($con"SELECT * FROM `users` WHERE `active` = '0'");
51
52 //loop through this script for each row found not active
53
54 while($row = mysqli_fetch_assoc($res)){
55
56 //check if the code from the row in the database matches the one from the user
57
58 if($code == md5($row['username']).$row['rtime']){
59
60 //if it does then activate there account and display success message
61
62 $res1 = mysqli_query($con,"UPDATE `users` SET `active` = '1' WHERE `id` = '" .$row['id']."'");
63
64 echo "<center>You have successfully activated your account!</center>";
65
66 }
67

68 }
69
70 }
71
72 ?>
73
74 </div>
75
76 </body>
77
78 </html>

There are two new things in this file, we use the GET method instead of POST and also we use a
while() loop. The get method simply gets data from the address bar at the top of the user’s browser (in
this case being the code sent with the email to their email address). The while() loop is perfecting for
checking through multiple rows of data selected from the database (in this case to see if there is a
match with the codes).

Overview so Far

So far you should’ve learned many new things if your new to PHP and successfully created a half of a
login system. The pages completed so far are –

• style.css

• functions.php

• login.php

• register.php

• activate.php

Some useful functions used so far are –

• mysqli_connect() – Connect to a mysql database

• mysqli_query() – Send querys to the database to get, insert or edit data

• trim() – Cut unwanted white space of the beginning and end of a string

• strip_tags() – Remove html and PHP tags from a string

• addslashes() – Add slashes to s string allowing quotes and speech marks to be used safely

• strlen() – Get the number of characters in a string

• preg_match() – Preg match is to match the formatting of a string

• mail() – Send mail from the server to the specified email address

• md5() – This calculates the md5 hash of a string


5. Forgotten Your Password?
Next up is our forgotten password page. If the user forgets their password, we can email it to them now
we know that they supplied a real email address because of the activation. So without further ado here’s
the commented code for forgot.php –

1 <?php
2
3 //allow sessions to be passed so we can see if the user is logged in
4
5 session_start();
6
7 //connect to the database so we can check, edit, or insert data to our users table
8
9 include('config.php');
10 //include out functions file giving us access to the protect() function made earlier
11
12 include "functions.php";
13
14 ?>
15
16 <html>
17
18 <head>
19
20 <title>Login with Users Online Tutorial</title>
21
22 <link rel="stylesheet" type="text/css" href="style.css" />
23
24 </head>
25
26 <body>
27
28 <?php
29
30 //Check to see if the forms submitted
31
32 if($_POST['submit']){
33
34 //if it is continue checks
35
36 //store the posted email to variable after protection
37
38 $email = protect($_POST['email']);
39
40 //check if the email box was not filled in
41
42 if(!$email){
43
44 //if it wasn't display error message
45
46 echo "<center>You need to fill in your <b>E-mail</b> address!</center>";
47
48 }else{
49
50 //else continue checking
51
52 //set the format to check the email against
53
54 $checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
55
56 //check if the email doesnt match the required format
57

if(!preg_match($checkemail, $email)){
58 if(!preg_match($checkemail, $email)){

59
60 //if not then display error message
61
62 echo "<center><b>E-mail</b> is not valid, must be name@server.tld!</center>";
63
64 }else{
65
66 //otherwise continue checking
67
68 //select all rows from the database where the emails match
69
70 $res = mysqli_query($con,"SELECT * FROM `users` WHERE `email` = '".$email."'");
71
72 $num = mysqli_num_rows($res);
73
74 //check if the number of row matched is equal to 0
75
76 if($num == 0){
77
78 //if it is display error message
79
80 echo "<center>The <b>E-mail</b> you supplied does not exist in our database!</center>";
81
82 }else{
83
84 //otherwise complete forgot pass function
85
86 //split the row into an associative array
87
88 $row = mysqli_fetch_assoc($res);
89
90 //send email containing their password to their email address
91
92 mail($email, 'Forgotten Password', "Here is your password: ".$row['password']."\n\nPlease try
not too lose it again!", 'From: noreply@yourwebsitehere.co.uk');
93
94 //display success message
95
96 echo "<center>An email has been sent too your email address containing your password!
</center>";
97
98 }
99
100 }
101
102 }
103
104 }
105
106 ?>
107
108 <div id="border">
109
110 <form action="forgot.php" method="post">
111
112 <table cellpadding="2" cellspacing="0" border="0">
113
114 <tr>
115
116 <td>Email: </td>
117
118 <td><input type="text" name="email" /></td>
119
120 </tr>
121
<tr>
122 <tr>

123
124 <td colspan="2" align="center"><input type="submit" name="submit" value="Send" /></td>
125
126 </tr>
127
128 <tr>
129
130 <td colspan="2" align="center"><a href="register.php">Register</a> | <a
href="login.php">Login</a></a></td>
131
132 </tr>
133
134 </table>
135
136 </form>
137
138 </div>
139
140 </body>
141
142 </html>

This page consists of nothing new therefore I will spend less time looking over it. One thing I do want to
mention is that if you haven’t noticed because we have been including our css file into every page the
layout we are using for each page is staying very similar keeping a nice smart design throughout the
whole website.

The next and final page we will be doing in this tutorial will be slightly different. This page has the check
to see if the user is logged in or not, and in this case displays all the users online at that current moment
(or to be precise within the past 50 seconds).

6. The Users Online Page


Okay so we have made it to the section of the website you need to be logged in to view. As I mentioned
before this one is going to be slightly different to the others because of the fact that we need to check if
the user is logged in or not. If they are not logged in and try to view the page we have a few options we
can do. The first being we can display an error message saying something along the lines of “You need
to be logged in to view this page!”, or we can redirect them back to the login page. For this tutorial I
think I’m going to use the error message method.

So here is the usersOnline.php page’s source –

1 <?php
2
//allow sessions to be passed so we can see if the user is logged in
3 //allow sessions to be passed so we can see if the user is logged in
4
5 session_start();
6
7 //connect to the database so we can check, edit, or insert data to our users table
8
9 include('config.php');
10
11 //include out functions file giving us access to the protect() function made earlier
12
13 include "functions.php";
14
15 ?>
16
17 <html>
18
19 <head>
20
21 <title>Login with Users Online Tutorial</title>
22
23 <link rel="stylesheet" type="text/css" href="style.css" />
24
25 </head>
26
27 <body>
28
29 <?php
30
31 //if the login session does not exist therefore meaning the user is not logged in
32
33 if(strcmp($_SESSION['uid'],"") == 0){
34
35 //display and error message
36
37 echo "<center>You need to be logged in to user this feature!</center>" ;
38
39 }else{
40
41 //otherwise continue the page
42
43 //this is out update script which should be used in each page to update the users online time
44
45 $time = date('U')+50;
46
47 $update = mysqli_query($con,"UPDATE `users` SET `online` = '" .$time."' WHERE `id` =
'".$_SESSION['uid']."'");
48
49 ?>
50
51 <div id="border">
52
53 <table cellpadding="2" cellspacing="0" border="0" width="100%">
54
55 <tr>
56
57 <td><b>Users Online:</b></td>
58
59 <td>
60
61 <?php
62
63 //select all rows where there online time is more than the current time
64
65 $res = mysqli_query($con,"SELECT * FROM `users` WHERE `online` > '".date('U')."'");
66
67 //loop for each row
68
while($row = mysqli_fetch_assoc($res)){
69 while($row = mysqli_fetch_assoc($res)){
70
71 //echo each username found to be online with a dash to split them
72
73 echo $row['username']." - ";
74
75 }
76
77 ?>
78
79 </td>
80
81 </tr>
82
83 <tr>
84
85 <td colspan="2" align="center"><a href="logout.php">Logout</a></td>
86
87 </tr>
88
89 </table>
90
91 </div>
92
93 <?php
94
95 //make sure you close the check if their online
96
97 }
98
99 ?>
100
101 </body>
102
103 </html>

As I mentioned, you can see this page is slightly different. Not only do we ensure that they are logged
in, but we update the online time keeping the online field ahead of the current time. Each time a page is
loaded with that script, it will update to put them online. Now we have one more final page to do and
then we are done. Once a user has logged in, he needs to be able to log out!

Logout.php

This has to be considered the easiest page to make which I am sure most of you are glad to hear. Now
here is the commented code for the logout.php file –

1 <?php
2
3 //allow sessions to be passed so we can see if the user is logged in
4
5 session_start();
6
7 //connect to the database so we can check, edit, or insert data to our users table
8
9 include('config.php');
10
11 //include out functions file giving us access to the protect() function made earlier
12
13 include "functions.php";
14
15 ?>
16
<html>
17 <html>
18
19 <head>
20
21 <title>Login with Users Online Tutorial</title>
22
23 <link rel="stylesheet" type="text/css" href="style.css" />
24
25 </head>
26
27 <body>
28
29 <?php
30
31 //check if the login session does no exist
32
33 if(strcmp($_SESSION['uid'],"") == 0){
34
35 //if it doesn't display an error message
36
37 echo "<center>You need to be logged in to log out!</center>" ;
38
39 }else{
40
41 //if it does continue checking
42
43 //update to set this users online field to the current time
44
45 mysqli_query($con,"UPDATE `users` SET `online` = '" .date('U')."' WHERE `id` =
'".$_SESSION['uid']."'");
46
47 //destroy all sessions canceling the login session
48
49 session_destroy();
50
51 //display success message
52
53 echo "<center>You have successfully logged out!</center>";
54
55 }
56
57 ?>
58
59 </body>
60
61 </html>

I think the comments in this file explain it enough, and I think your PHP knowledge now should be much
higher and you should be able to understand most of this now.

Thanks a lot
Masud Alam

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka,
Bangladesh. I’m a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of
leadership positions at Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development
Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I
worked on ERP software and web development., but now i’m a founder and CEO of TechBeeo
Software Company Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional
web development course at w3programmers Training Institute – a leading Training Institute in the
country.

P H P & M Y S Q
P R O J E C T S

T A GP GH EP D L , PO HG PI N R EP G
A ,P
IG SHE TP R AF TO IR OG NO, P T HP PAP GA E ES M S A W I OL R
A C T I V A T I O N

29 comments on “Build a Full-Featured Login System with PHP”

REPLY
A L A M G I R K A B I R
1 3 J U L Y , 2 0 1 2 A T 6 : 1 1 A M

Great Job. Every part is specific. So that , anyone can understand. Great.

REPLY
F U A D H A S A N
1 4 J U L Y , 2 0 1 2 A T 2 : 5 3 A M

Excellent!!!!!!

REPLY
D A V U D N A Z A R I
1 8 S E P T E M B E R , 2 0 1 2 A T 9 : 1 7 P M

Tank you
REPLY
L
2 9 O C T O B E R , 2 0 1 2 A T 1 1 : 1 3 P M

echo ? There is something like CSS


old and unsecure mysql__ and md5()

REPLY
F U A D H A S A N
2 1 D E C E M B E R , 2 0 1 2 A T 2 : 0 5 P M

really aw some. Sir you are really great.


Excellent.

REPLY
K A M R U L H A S A N
6 F E B R U A R Y , 2 0 1 3 A T 1 2 : 2 9 A M

I have some confusions like, here you have shown login.php file for 2 times-
1. First of all only with html code
2. Secondly with php code
which one should i consider for this project ??
Though i consider for the Second one.

Why this message is coming –

Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers


already sent (output started at /home/lrpaid/public_html/test/Login/activate.php:2) in
/home/lrpaid/public_html/test/Login/activate.php on line 6

REPLY
S I R I V U R I R A J U
4 M A R C H , 2 0 1 3 A T 3 : 2 0 P M

you are tutorials is very good…


its easy to understand
REPLY
M A M U N H O Q U E
8 A P R I L , 2 0 1 3 A T 1 1 : 4 7 P M

I saw on point 5. Forgotten Password part, there this script send the password to user email but
my question is previously pasword was MD5 encrypted so is it working ?

N.B . mail($email, ‘Forgotten Password’, “Here is your password: “.$row[‘password’].”\n\nPlease


try not too lose it again!”, ‘From: noreply@yourwebsitehere.co.uk‘);

REPLY
A D N A N
2 1 A P R I L , 2 0 1 3 A T 1 2 : 5 6 P M

It was great but a li’l bit over coding don’t u think? I mean u could do it much easier and shorter
with OOP

REPLY
A R U N
2 4 A P R I L , 2 0 1 3 A T 1 2 : 4 0 P M

Can u please share ur codings using OOP… plz

REPLY
M A S U D ( A UL TA HM O
A R )
2 5 A P R I L , 2 0 1 3 A T 5 : 5 3 A M

u can follow this article


http://www.w3programmers.com/login-and-registration-using-oop/

REPLY
S A I F
1 0 J U L Y , 2 0 1 3 A T 8 : 4 5 A M

Its really great. amazing !!!


I have a problem: The link for the email for activation is not working. What is to be done
otherwise, please get the solution

REPLY
S A I F
1 4 J U L Y , 2 0 1 3 A T 1 0 : 2 2 A M

It’s all great. But the register is not working and the user can not activate his account. Why?

REPLY
L U C K Y
2 9 J U L Y , 2 0 1 3 A T 8 : 0 8 A M

Really nice code, it helped me…, it is very simple and effective.


Thanks a lot…!!!

REPLY
Z A K I R
1 5 S E P T E M B E R , 2 0 1 3 A T 7 : 5 8 P M

Every thing is good but remember option is missing.

REPLY
P H P L O V E R
9 N O V E M B E R , 2 0 1 3 A T 7 : 0 2 P M

it is not secure, because there is no prepared statement is used…

REPLY
T A R U N
4 D E C E M B E R , 2 0 1 3 A T 8 : 0 5 A M

this code i want to download where is surce code and zip code
REPLY
R A S H A D
3 J U N E , 2 0 1 4 A T 1 1 : 0 8 P M

isset() function in php determines whether a variable is set and is not NULL. It returns a
boolean value, that is, if the variable is set it will return true and if the variable value is null it will
return false.

So need to use if (isset($_POST['submit'])) to check the form submitted or not.

REPLY
A D E D I V I
1 J A N U A R Y , 2 0 1 5 A T 4 : 4 7 A M

when click register button, i got the following error pls help.

( ! ) Notice: Undefined variable: INFO in C:\wamp\www\on\register.php on line 156

Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and
"smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\on\register.php on line 156

thank you boss

REPLY
M D F A R I D K H A N D A K E R
1 6 F E B R U A R Y , 2 0 1 5 A T 7 : 0 2 A M

Musud bi Awsome.

REPLY
D E E P J Y O T I B A I S H Y A
3 N O V E M B E R , 2 0 1 7 A T 3 : 4 5 P M

Sir, how to add profile pic upload option .


REPLY
M D A M I N U L H A Q U E
2 0 M A R C H , 2 0 1 8 A T 2 : 5 7 P M

Sir,
Thank you very much for your nice tutorial. And i hope that, we will get more tutorial about Php,
Javascript & others.

REPLY
A J I T
7 A P R I L , 2 0 1 8 A T 3 : 2 4 P M

awesome job. Very much clear.

REPLY
S Y E D I M R A N
1 0 M A Y , 2 0 1 8 A T 1 0 : 0 3 A M

Hi thanks Sir, problem is user is not activating after clicking on email link, database is working.
record generated just after submit register form, but when i click the link from email. its not
showing anything blank page

REPLY
D A N I E L
6 S E P T E M B E R , 2 0 1 8 A T 9 : 0 4 P M

excellent. job

REPLY
S O W E T
1 3 S E P T E M B E R , 2 0 1 8 A T 9 : 3 0 P M

GREAT JOB. GOD BLESS U. PLS CAN I GET OOP OF THIS? THANKS SIR

REPLY
J E F F D
2 4 S E P T E M B E R , 2 0 1 8 A T 4 : 3 8 A M

encountered the following error:

Notice: Undefined index: submit in C:\xampp\htdocs\login\login.php on line 23

how do i fix?

REPLY
M D F A H M I D U Z Z A M A N S A G A R
3 N O V E M B E R , 2 0 1 8 A T 1 0 : 3 3 A M

Awesome sir

REPLY
M A R L E Y
1 2 N O V E M B E R , 2 0 1 8 A T 3 : 1 5 P M

I am a beginner, where should I put it? can someone help me here?

INSERT INTO users( id, username,


PASSWORD , online, email, active, rtime )
VALUES ( 1, ‘testing’, ‘testing’, 0, ‘fake@noemail.co.uk’, 0, 0 )

Leave a Reply
YOUR EMAIL ADDRESS WILL NOT BE PUBLISHED. REQUIRED FIELDS ARE MARKED
*
C O M M E N T

N A *M E

E M *A I L

POST COMMENT

Categories

PHP & MySQL Projects

PHP Basics

PHP Arrays, Strings and Numbers

PHP Control Structures

CODEIGNITER

JQUERY and AJAX with PHP

JAVASCRIPT

MySQL Tutorial

WordPress

PHP Object Oriented Programming


PHP Security and Exceptions

PHP PDO, MySQLi and SQLITE

PHP Date Time and RegEx

PHP File, Mail, Session and Cookie

Useful PHP Functions and Features

PHP Design patterns

JSON, XML and Web Services

Standard PHP Library (SPL)

Zend Framework 2.x

Laravel

FAT FREE FRAMEWORK

Facebook

Joomla

Twitter Bootstrap

YII

SASS and LESS

Drupal

HTML and CSS

Angular JS

CakePHP

Android Application Development

Magento
Symfony

Python

Node.js

PHP Excercises

Bangla Article

Join Our Group

W3programmers
Facebook Group · 6,155 members

Join Group

w3programmers is the Official group of the


www.w3programmers.com website. Here you
can discuss everything about Web
Development & Technologies such...

JANUARY 2019
S S M T W T F
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
« Dec

C O P Y R I G H T © 2 0
No announcement available or all announcement expired.

You might also like