0% found this document useful (0 votes)
233 views21 pages

Login With Session Using PHP and MYSQL Database

Uploaded by

pravesh koirala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
233 views21 pages

Login With Session Using PHP and MYSQL Database

Uploaded by

pravesh koirala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Login with session using PHP and MYSQL

database

What is session?
The session is used to access the various pages of an entire website. A
session creates a temporary directory on the server. With the help of
session variables and their value is stored.

In the previous tutorial, we discussed the session in PHP. A session is


used to store the information on the server rather than the client
computer.

Create a MYSQL database table using Query


Whenever we create a login system we need an MYSQL [Link]
can logIn by fetching user data from the MYSQL database table. In the
previous tutorial, we created a simple login form using PHP and MYSQL
databse. Let's create a database table using the MYSQL query.

CREATE TABLE `users` (

`id` INT( 50 ) NOT NULL ,

`uname` VARCHAR( 40 ) NOT NULL ,

`upassword` VARCHAR( 40 ) NOT NULL

) ENGINE = INNODB DEFAULT CHARSET = latin1;

Insert data into MYSQL database table for


Login with session
To insert the data into the table, you can use the registration form or
insert query. When you create a login form, you have to fetch the
data. Unless you have data in the database, you will not be able to
create the login system. You can use the registration form to insert
data or you can perform insert query to insert data into the database
table. Let's insert the data into database table using MYSQL query.

INSERT INTO `users` (`id`, `uname`, `upassword`) VALUES

(1, 'admin', 'admin@123');

Create a connection file to connect MYSQL


and PHP
The config file hanles the connection between PHP and MYSQL
database.
Now, create a file and save with name and extension "[Link]".

<?php

$databaseHost = '[Link]';//or localhost

$databaseName = 'project'; // your db_name

$databaseUsername = 'root'; // root by default for localhost

$databasePassword = ''; // by defualt empty for localhost

$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword,


$databaseName);

?>

In the above config file, we are used mysqli_connect() function for a


new connection. We are passed this information as a parameter and
stored in a variable $mysqli. You can change database host, database
name, database username, and database Password according to your
needs.

Login with session pages structure in PHP


In this small project, we use the session to access session data on
pages of the website. We create pages to access session data.

After the destroyed session, unknown persons cannot access the


pages. This is the main advantage of PHP session .
Let's create some pages .

[Link] -

After session created the user redirects to main page([Link]).


[Link] -
The login page handles the user input information. This is the starting
page of login system. Without login success, user cannot access all
pages.
[Link] -
This is the action file of the login form. That includes all the PHP script.
We create a session in this file.
[Link] -
Access session on page 1 after login.
[Link] -
Access session on page 2 after login.
[Link]-
Access session on page 3 after login.
[Link] -
We use session destroy to the destroyed complete session. This is
used to logout. After logout, the user cannot access another pages.

The session is recommended to start the session at the beginning of


every page. [Link] is a home page.
When a user wants to visit [Link] without login the session returns
to the login page. The user can not directly access the [Link] page
without login.

If any user wants to access any page session return to the login page.
First of all, the user should log in then access all pages direct till the
session destroyed?

Let's implement a complete Login system using PHP and MYSQL


database.

Make a login form for user login using PHP


session
Now, we create an HTML form. The HTML form is used to input
information from the user. A user enters a username and password
using HTML form. This is the beginning of the login system in PHP. The
user files a username and password and clicks the login button. If the
username and password are matched, the user logs in. If the password
and username are incorrect, an error message is displayed on the
same login form. Let's create an HTML form.

[Link]
<html>

<head>

</head>

<center>

<fieldset>

<legend>Login </legend>

<form action="[Link]" method="POST"><br><br>

Username:<input type="text" required="" name="uname"><br><br>

Password:<input type="text" required="" name="upassword"><br><br>


<input type="submit" value="Login" name="sub">

<br>

<?php

if(isset($_REQUEST["err"]))

$msg="Invalid username or Password";

?>

<p style="color:red;">

<?php if(isset($msg))

echo $msg;

?>

</p>

</form>

</fieldset>
</center>
</html>

In the above form, we defined the action "[Link]". The login


process file handles the backend login process.

Create PHP code for login using session


We create form handling scripts in PHP. This file handles the MYSQL
and HTML form functional.
[Link] of all ,start session at the beginning of the page

2. We include the config [Link] can user include()


function and require() function to include [Link] file.

3. Use if condition to set form fields data on the button.

4. Here, we use the request variable. The request variable contains


the PHP POST method values.

5. Use the MYSQL select query.

6. Store session variable data.

7. Use header() function . The header() function is used to redirect


another page after login. If the error occurred ,redirects to the same
login form. If user id and password are matched , redirects to
[Link] page else error shows result "please enter valid id and
password".

[Link]
<?php

session_start ();

include("[Link]");

if(isset($_REQUEST['sub']))

$a = $_REQUEST['uname'];

$b = $_REQUEST['upassword'];
$res = mysqli_query($cser,"select* from users where uname='$a'and upassword='
$b'");

$result=mysqli_fetch_array($res);

if($result)

$_SESSION["login"]="1";

header("location:[Link]");

else

header("location:[Link]?err=1");

?>

Create the main page after login success


Now, create the main page [Link] page. It is the index page of the
login system. First of all, we start the session by session_start()
function at the beginning of the page. After that, we check if the
session is not created than return to the login page ([Link] ).

[Link]
<?php

session_start ();

if(!isset($_SESSION["login"]))
header("location:[Link]");

?>

<h1>Hey ! welcome to main page .</h1>

<a href="[Link]"><h2><font color="">PAGE 1</font></h2>

<a href="[Link]"><h2><font color="">PAGE 2</font></h2>

<a href="[Link]"><h2><font color="">PAGE 3</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2>

Now, We create more pages (page 1, page2, and page 3) as example


to access session. All pages include session_start() function at the
beginning of the page. Start session is the must for entire pages.

Users can access all pages by the login. If the session is not created or
destroyed then redirect to the [Link] page.

A website contains a lot of pages. These pages help you understand


how to access sessions on the pages of the website.

If the session is destroyed, the user can not access any page of the
website. An authenticated user can access the entire pages of the
website. That's why the session is used for security purposes. Secure
your website data from unknown users.
Let's create another page.

Make another page 1 to access login with


session
Create another page. Start the session on every single page of the
website. Use if condition, If the session is set then stay on the page
and if the session is destroyed then redirect to [Link] After this PHP
code, you can create and design your page according to your need but
do not remove PHP session code at the top of pages. Follow these
instructions for other website pages.

[Link]
<?php

session_start ();

if(!isset($_SESSION["login"]))

header("location:[Link]");

?>

<h1> Welcome to page 1 </h1>

<a href="[Link]"><h2><font color="">PAGE 1</font></h2>

<a href="[Link]"><h2><font color="">PAGE 2</font></h2>

<a href="[Link]"><h2><font color="">PAGE 3</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2></a>

Make another page 2 to access session after


login
[Link]
<?php

session_start ();

if(!isset($_SESSION["login"]))

header("location:[Link]");

?>

<h1> Welcome to page 2 </h1>

<a href="[Link]"><h2><font color="">PAGE 1</font></h2>

<a href="[Link]"><h2><font color="">PAGE 2</font></h2>

<a href="[Link]"><h2><font color="">PAGE 3</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2></a>

Make another page 3 to access session


[Link]
<?php

session_start ();
if(!isset($_SESSION["login"]))

header("location:[Link]");

?>

<h1> Welcome to page 3 </h1>

<a href="[Link]"><h2><font color="">PAGE 1</font></h2>

<a href="[Link]"><h2><font color="">PAGE 2</font></h2>

<a href="[Link]"><h2><font color="">PAGE 3</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2></a>

Logout page using session destroyed function


in PHP
Page Logout means that you are destroying a complete session. After
destroying the session, an unknown user cannot access authorized
pages. This is the most important thing to secure sensitive data from
an unknown user. The authorized user can log in and access all pages.
The session_destroy() function is used to destroy all sessions.

[Link]
<?php
session_start ();

session_destroy();

header("location:[Link]")

?>

What is cookie ?
Cookie is a small file that is stored on the client computer. Cookie
depends on the client-side, not on the server-side. In simple words, a
small file stored on the client computer through the server. The cookie
is not stored on the server. In other words, If you log in after 5 days,
you do not require to fill up any id and password. The user is logged in
without entering a username and password. We can set a cookie
expiry time for 1 month or more. If we set 1 month. After 1 month you
can not access the cookie. so It’s all done through the cookies. In the
previous tutorial, we discussed the cookies in php. Here, we create a
complete login system using PHP and MySQL database.

Create an MYSQL database table using query


We have to create a MySQL database for the login system using
cookies. In the MySQL database, we create table, through which we
create the login system using PHP and MySQL database. Let's create a
table using query.

CREATE TABLE `users` (

`id` INT( 50 ) NOT NULL ,

`uname` VARCHAR( 40 ) NOT NULL ,

`upassword` VARCHAR( 40 ) NOT NULL

) ENGINE = INNODB DEFAULT CHARSET = latin1;


Insert data into the database table for login
with cookies using PHP
Insert the data into the table. We can use the registration form or
MYSQL insert query. When you create a login form, you have to fetch
the data. Unless you have data in the database, you will not be able to
create the login system using cookies. You can use the registration
form to insert data or you can perform insert query to insert data into
the MYSQL database table. Let's insert the data into database table
using MYSQL query.

INSERT INTO `users` (`id`, `uname`, `upassword`) VALUES (1, 'admin'


, 'admin@123');

Create a connection file


The config file hanles the connection between PHP form and MYSQL
database. Now, create a file and save with name and extension
"[Link]".

<?php

$databaseHost = '[Link]';//or localhost

$databaseName = 'project'; // your db_name

$databaseUsername = 'root'; // root by default for localhost

$databasePassword = ''; // by defualt empty for localhost

$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword,


$databaseName);

?>
In above config file , we used mysqli_connect() function for a new
connection. We passed these information as parameters and stored in
a variable $mysqli. You can change database host, database name,
database username, and database password according to your need.

Create a HTML login form included PHP code


Now, we create an HTML form. The user fills the username, password,
and clicks on the login button. This is the starting page of login with
cookies. In this HTML form, we create two input box and a submit
button. First input box for username and a second input box for
password. Here, we use if condition . If a username or password does
not exists then display the message Invalid username or password.

[Link]
<html>

<fieldset>

<legend>Login </legend>

<form action="[Link]" method="POST"><br><br>

Username:<input type="text" required="" name="uname"><br><br>

Password:<input type="text" required="" name="upassword"><br><br>

<input type="checkbox" value="1" name="remember">keep me login:

<input type="submit" value="Login" name="sub">

<br>

<?php

if(isset($_REQUEST["err"]))

$msg="Invalid username or Password";

?>

<p style="color:red;">

<?php if(isset($msg))
{

echo $msg;

?>

</p>

</form>

</fieldset>
</center>
</html>

Create a PHP script for login system with


cookies
Now, we create a PHP script for form handling. The PHP code contains
the form data and MYSQL query. The [Link] file handles the
part of database base connectivity and login process.
[Link] config file at the beginning of [Link] can use PHP include()
function and PHP require() function to include and require a config file.
[Link] if condition and set the form values on button.

3. Select query for match the username and password from the
database if username and password are not matched then return to
the login page and if username and password are matched then access
the pages within the time duration.

[Link] the cookie for 60 seconds. After 60 seconds, the user will be
logged out. In the previous tutorial, we discussed completely PHP
cookies.

5. Use header() function after login success or not. If the login


succcess then redirect to the index page. If the login does not success
then redirect to the same login page.

6. You do not need to start cookies in every single page like session.

[Link]
<?php

$cser=mysqli_connect("localhost","root","","project") or die("connection fail


ed:".mysqli_error());

if(isset($_REQUEST['sub']))

$a = $_REQUEST['uname'];

$b = $_REQUEST['upassword'];

$res = mysqli_query($cser,"select* from users where uname='$a'and upassword='


$b'");

$result=mysqli_fetch_array($res);

if($result)

if(isset($_REQUEST["remember"]) && $_REQUEST["remember"]==1)

setcookie("login","1",time()+60);// second on page time

else

setcookie("login","1");

header("location:[Link]");
}

else

header("location:[Link]?err=1");

?>

Make the main page after login success


Now, we create a Home Page([Link]) page. On the home page,
we check if the cookie is not set. If the cookie is not set then you can
not access the page and redirect to the login page . and if the cookie is
set then you can access any kind of page of the website.

[Link]
<?php

if(!isset($_COOKIE["login"]))// $_COOKIE is a variable and login is a cookie


name

header("location:[Link]");

?>

<h1>Hey ! welcome to main page .</h1>


<a href="[Link]"><h2><font color="">PAGE 1</font></h2>

<a href="[Link]"><h2><font color="">PAGE 2</font></h2>

<a href="[Link]"><h2><font color="">PAGE 3</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2>

Create another page 1 to access the cookie


A website contains lot of [Link],you find the another pages
example. You can create another page of the website like this. Create
another pages.

We create the page 1 ,page2 ,and page 3 as to access cookies . In


these pages(page 1 ,page 2 and page 3 ) we include a condtion . If the
cookie is not set then redirect to login page ([Link]) and if cookie is
set then stay on same page.

Let's create another pages.

[Link]
<?php

if(!isset($_COOKIE["login"]))

header("location:[Link]");

?>

<h1> Welcome to page 1 </h1>

<table>

<a href="[Link]"><h2><font color="">PAGE 1</font></h2>

<a href="[Link]"><h2><font color="">PAGE 2</font></h2>

<a href="[Link]"><h2><font color="">PAGE 3</font></h2>


<a href="[Link]"><h2><font color="red">Logout</font></h2>

Create another page 2 to access the cookie


Here,we create another page 2 and access the cookie.

[Link]
<?php

if(!isset($_COOKIE["login"]))

header("location:[Link]");

?>

<h1> Welcome to page 2 </h1>

<table>

<a href="[Link]"><h2><font color="">PAGE 1</font></h2>

<a href="[Link]"><h2><font color="">PAGE 2</font></h2>

<a href="[Link]"><h2><font color="">PAGE 3</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2>

Create another page 3 to access the cookie


Create another page 3 and access cookie. If cookie is not set or
deleteted the redirect to login page otherwise stay on page.

[Link]
<?php

if(!isset($_COOKIE["login"]))

header("location:[Link]");

?>

<h1> Welcome to page 3 </h1>

<table>

<a href="[Link]"><h2><font color="">PAGE 1</font></h2>

<a href="[Link]"><h2><font color="">PAGE 2</font></h2>

<a href="[Link]"><h2><font color="">PAGE 3</font></h2>

<a href="[Link]"><h2><font color="red">Logout</font></h2>

Logout | delete the cookies


Logout is a process of delete cookies. After delete cookies, unknown
users cannot access the page. You can use setcookie() function and
expiry time. This is known as destroyed cookies. Delete cookies by
secookie() function .

[Link]
<?php

setcookie("login","",time()-1);//for delete the cookie //destroy the cookie

header("location:[Link]")

?>

You might also like