SlideShare a Scribd company logo
WELCOME
INTRODUCTION TO PHP
SESSIONS AND COOKIES
What you Benefit ???
By the end of this session you will learn
● How to use Sessions and Cookies to maintain the state among
multiple requests.
TASK OF THE DAY
Create a session when a user log in to his account. When user logout from his
account the session should expire
LOGIN PAGE
INTRODUCTION TO PHP SESSIONS AND
COOKIES
Introduction To PHP Sessions And
Cookies
We had already tried passing data to a server .
But..how the server knows the user from which the requests are
received…?
COOKIES
Cookies
•HTTP is a stateless protocol; this means that the web server does not
know (or care) whether two requests comes from the same user or
not; it just handles each request without regard to the context in
which it happens.
•Cookies are used to maintain the state in between requests—even
when they occur at large time intervals from each other.
•Cookies allow your applications to store a small amount of textual
data (typically,4-6kB) on a Web client browser.
•There are a number of possible uses for cookies, although their most
common one is maintaining state of a user
Creating A Cookie
• setcookie(“userid", "100", time() + 86400);
• This simply sets a cookie variable named “userid” with value “100” and this
variable value will be available till next 86400 seconds from current time
Cookie variable name
variable value
Expiration time.
Accessing a Cookie
• echo $_COOKIE[’userid’]; // prints 100
• Cookie as array
– setcookie("test_cookie[0]", "foo");
– setcookie("test_cookie[1]", "bar");
– setcookie("test_cookie[2]", "bar");
– var_dump($_COOKIE[‘test_cookie’]);
Destroying A Cookie
•There is no special methods to destroy a cookie, We achieve it by
setting the cookie time into a past time so that it destroys it
– Eg : setcookie(‘userid’,100,time()-100);
SESSIONS
Sessions
•Session serve the same purpose of cookies that is sessions are used to
maintain the state in between requests
•Session can be started in two ways in PHP
– By changing the session.auto_start configuration setting in php.ini
– Calling session_start() on the beginning of each pages wherever you
use session(Most common way)
Note: session_start() must be called before any output is sent to the
browser
Creating and accessing session
• Once session is started you can create and access
session variables like any other arrays in PHP
– $_SESSION[‘userid’] = 100;
– echo $_SESSION[‘userid’]; //prints 100
Session variable name
variable value
Destroying A Session
•There are two methods to destroy a session variable
1. Using unset() function
• Eg unset($_SESSION[‘userid’])
1. Calling session_destroy() method. This will effectively destroy all the
session variables. So for deleting only one variable you should go for
the previous method
• Session_destroy()
Let’s try implementing with our task
Step 1
Goto Login_baabtra.php page and set form action to Profile.php page
<form name=”login” action=”login_action.php” method=”post”>
Step 2
Login_action.php Page
Create database connection here
mysql_connect('localhost','root','');
mysql_select_db("Baabtra");
$result=mysql_query("select * from tbl_user where
vchr_user_name='$username'and vchr_password='$password'");
Step 3
Login_action.php Page
Check whether id is valid or not.if valid user then create session
if(mysql_num_rows($result)){
while($row=mysql_fetch_array($result)){
session_start();
$_SESSION['user_id']=$row['pk_int_user_id'];
header(‘Location: profile.php’);
}
}
checks whether there is any
resultant
Step 3
Login_action.php Page
Check whether id is valid or not.if valid user then create session
if(mysql_num_rows($result)){
while($row=mysql_fetch_array($result)){
session_start();
$_SESSION['user_id']=$row['pk_int_user_id'];
header(‘Location: profile.php’);
}
}
starts a session
Step 3
Login_action.php Page
Check whether id is valid or not.if valid user then create session
if(mysql_num_rows($result)){
while($row=mysql_fetch_array($result)){
session_start();
$_SESSION['user_id']=$row['pk_int_user_id'];
header(‘Location: profile.php’);
}
} sets a session variable
userid
with value of pk_int_user_id
field of the resultant set
Step 3
Login_action.php Page
Check whether id is valid or not.if valid user then create session
if(mysql_num_rows($result)){
while($row=mysql_fetch_array($result)){
session_start();
$_SESSION['user_id']=$row['pk_int_user_id'];
header(‘Location: profile.php’);
}
} sets a session variable
userid
with value of pk_int_user_id
field of the resultant set
Step 3
Login_action.php Page
Check whether id is valid or not.if valid user then create session
if(mysql_num_rows($result)){
while($row=mysql_fetch_array($result)){
session_start();
$_SESSION['user_id']=$row['pk_int_user_id'];
header(‘Location: profile.php’);
}
}
sets a session variable
userid
with value of pk_int_user_id
field of the resultant set
Step 3
Login_action.php Page
Check whether id is valid or not.if valid user then create session
if(mysql_num_rows($result)){
while($row=mysql_fetch_array($result)){
session_start();
$_SESSION['user_id']=$row['pk_int_user_id'];
header(‘Location: profile.php’);
}
}
header function is used for
page redirection
Step 4
Design a profile Page and Create a link for Logout
Step 5
Go to profile page and display Qualification details of that particular user
using session variable.
Step 5
Profile.php
session_start();
$user_id=$_SESSION['user_id'];
mysql_connect('localhost','root','');
mysql_select_db("Baabtra");
$result=mysql_query("select * from tbl_academic_qualificaion where
fk_int_user_id='$user_id'");
echo “ qualification name-----college--------percentage--------passout”;
while($data=mysql_fetch_assoc($result)){
echo $data['vchr_qualification_name'];
echo $data['vchr_qualification_name'];
echo $data['int_percentage'];
echo $data['dat_passout_date'];
}
Step 5
Profile.php
session_start();
$user_id=$_SESSION['user_id'];
mysql_connect('localhost','root','');
mysql_select_db("Baabtra");
$result=mysql_query("select * from tbl_academic_qualificaion where
fk_int_user_id='$user_id'");
echo “ qualification name-----college--------percentage--------passout”;
while($data=mysql_fetch_assoc($result)){
echo $data['vchr_qualification_name'];
echo $data['vchr_qualification_name'];
echo $data['int_percentage'];
echo $data['dat_passout_date'];
}
fetches the session variable
user_id and stores to
variable $userid
Step 5
Profile.php
session_start();
$user_id=$_SESSION['user_id'];
mysql_connect('localhost','root','');
mysql_select_db("Baabtra");
$result=mysql_query("select * from tbl_academic_qualificaion where
fk_int_user_id='$user_id'");
echo “ qualification name-----college--------percentage--------passout”;
while($data=mysql_fetch_assoc($result)){
echo $data['vchr_qualification_name'];
echo $data['vchr_qualification_name'];
echo $data['int_percentage'];
echo $data['dat_passout_date'];
}
selects the qualification
details of the user that
matches with session value
Step 6
Destroy session on Logout
Step 6
Logout.php
unset($_SESSION[‘user_id’]);
header(‘Location: Login_baabtra.php’);
Comparison
Cookies are stored in the user's
browser
A cookie can keep information in
the user's browser until deleted
by user or set as per the timer. It
will not be destroyed even if you
close the browser.
Cookies can only store string
We can save cookie for future
reference
Sessions are stored in server
A session is available as long as the
browser is opened. User cant disable
the session. It will be destroyed if you
close the browser
Can store not only strings but also
objects
session cant be.
Cookies Session
END OF THE SESSION
Ad

More Related Content

What's hot (20)

Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
Ahmed Swilam
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptx
ShitalGhotekar
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
Vibrant Technologies & Computers
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
Digital Insights - Digital Marketing Agency
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
priya Nithya
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
Vibrant Technologies & Computers
 
PHP
PHPPHP
PHP
Steve Fort
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
Dom
DomDom
Dom
Rakshita Upadhyay
 
php
phpphp
php
ajeetjhajharia
 
Php array
Php arrayPhp array
Php array
Nikul Shah
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
Nisa Soomro
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
Morshedul Arefin
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
vishal choudhary
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
Arti Parab Academics
 
HTTP Request and Response Structure
HTTP Request and Response StructureHTTP Request and Response Structure
HTTP Request and Response Structure
BhagyashreeGajera1
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 

Viewers also liked (17)

Cookie and session
Cookie and sessionCookie and session
Cookie and session
Aashish Ghale
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
Lena Petsenchuk
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
Programmer Blog
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
Introduction to php web programming - sessions and cookies
Introduction to php   web programming - sessions and cookiesIntroduction to php   web programming - sessions and cookies
Introduction to php web programming - sessions and cookies
baabtra.com - No. 1 supplier of quality freshers
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and Authentication
Gerard Sychay
 
Cookies PowerPoint
Cookies PowerPointCookies PowerPoint
Cookies PowerPoint
emurfield
 
Web Cookies
Web CookiesWeb Cookies
Web Cookies
apwebco
 
Pakistan's mountain ranges
Pakistan's mountain rangesPakistan's mountain ranges
Pakistan's mountain ranges
tehseen bukhari
 
Mountains In Pakistan
Mountains In PakistanMountains In Pakistan
Mountains In Pakistan
Ayesha Shoukat
 
PHP: Cookies
PHP: CookiesPHP: Cookies
PHP: Cookies
Mario Raul PEREZ
 
Plains, plateaus and deserts in pakistan
Plains, plateaus and deserts in pakistanPlains, plateaus and deserts in pakistan
Plains, plateaus and deserts in pakistan
Aqsa Manzoor
 
Mountains of Pakistan any physiography
Mountains of Pakistan any physiography Mountains of Pakistan any physiography
Mountains of Pakistan any physiography
GCUF
 
Physical features of pakistan
Physical features of pakistanPhysical features of pakistan
Physical features of pakistan
Amad Qurashi
 
Geography of Pakistan
Geography of PakistanGeography of Pakistan
Geography of Pakistan
Ali Faizan Wattoo
 
Presentation on Internet Cookies
Presentation on Internet CookiesPresentation on Internet Cookies
Presentation on Internet Cookies
Ritika Barethia
 
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
Slides For Operating System Concepts By Silberschatz Galvin And GagneSlides For Operating System Concepts By Silberschatz Galvin And Gagne
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
sarankumar4445
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
Programmer Blog
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and Authentication
Gerard Sychay
 
Cookies PowerPoint
Cookies PowerPointCookies PowerPoint
Cookies PowerPoint
emurfield
 
Web Cookies
Web CookiesWeb Cookies
Web Cookies
apwebco
 
Pakistan's mountain ranges
Pakistan's mountain rangesPakistan's mountain ranges
Pakistan's mountain ranges
tehseen bukhari
 
Plains, plateaus and deserts in pakistan
Plains, plateaus and deserts in pakistanPlains, plateaus and deserts in pakistan
Plains, plateaus and deserts in pakistan
Aqsa Manzoor
 
Mountains of Pakistan any physiography
Mountains of Pakistan any physiography Mountains of Pakistan any physiography
Mountains of Pakistan any physiography
GCUF
 
Physical features of pakistan
Physical features of pakistanPhysical features of pakistan
Physical features of pakistan
Amad Qurashi
 
Presentation on Internet Cookies
Presentation on Internet CookiesPresentation on Internet Cookies
Presentation on Internet Cookies
Ritika Barethia
 
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
Slides For Operating System Concepts By Silberschatz Galvin And GagneSlides For Operating System Concepts By Silberschatz Galvin And Gagne
Slides For Operating System Concepts By Silberschatz Galvin And Gagne
sarankumar4445
 
Ad

Similar to Php sessions & cookies (20)

Lecture8 php page control by okello erick
Lecture8 php page control by okello erickLecture8 php page control by okello erick
Lecture8 php page control by okello erick
okelloerick
 
season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)
kunjan shah
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
HumphreyOwuor1
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In Php
Harit Kothari
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
Degu8
 
Manish
ManishManish
Manish
Manish Jain
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
SreejithVP7
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
pondypaiyan
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Sessions n cookies
baabtra.com - No. 1 supplier of quality freshers
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
Jalpesh Vasa
 
Php session
Php sessionPhp session
Php session
argusacademy
 
17 sessions
17 sessions17 sessions
17 sessions
Abhijit Gaikwad
 
Security in php
Security in phpSecurity in php
Security in php
Jalpesh Vasa
 
Authentication
AuthenticationAuthentication
Authentication
soon
 
Jsp session tracking
Jsp   session trackingJsp   session tracking
Jsp session tracking
rvarshneyp
 
FP512 Cookies sessions
FP512 Cookies sessionsFP512 Cookies sessions
FP512 Cookies sessions
Fatin Fatihayah
 
lecture 13.pptx
lecture 13.pptxlecture 13.pptx
lecture 13.pptx
ITNet
 
SessionTrackServlets.pptx
SessionTrackServlets.pptxSessionTrackServlets.pptx
SessionTrackServlets.pptx
Ranjeet Reddy
 
ASP.NET-Web Programming - Sessions and Cookies
ASP.NET-Web Programming - Sessions and CookiesASP.NET-Web Programming - Sessions and Cookies
ASP.NET-Web Programming - Sessions and Cookies
baabtra.com - No. 1 supplier of quality freshers
 
State management in ASP.NET
State management in ASP.NETState management in ASP.NET
State management in ASP.NET
Om Vikram Thapa
 
Lecture8 php page control by okello erick
Lecture8 php page control by okello erickLecture8 php page control by okello erick
Lecture8 php page control by okello erick
okelloerick
 
season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)
kunjan shah
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
HumphreyOwuor1
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In Php
Harit Kothari
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
Degu8
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
SreejithVP7
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
pondypaiyan
 
Authentication
AuthenticationAuthentication
Authentication
soon
 
Jsp session tracking
Jsp   session trackingJsp   session tracking
Jsp session tracking
rvarshneyp
 
lecture 13.pptx
lecture 13.pptxlecture 13.pptx
lecture 13.pptx
ITNet
 
SessionTrackServlets.pptx
SessionTrackServlets.pptxSessionTrackServlets.pptx
SessionTrackServlets.pptx
Ranjeet Reddy
 
State management in ASP.NET
State management in ASP.NETState management in ASP.NET
State management in ASP.NET
Om Vikram Thapa
 
Ad

More from baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
baabtra.com - No. 1 supplier of quality freshers
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
baabtra.com - No. 1 supplier of quality freshers
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
baabtra.com - No. 1 supplier of quality freshers
 
Blue brain
Blue brainBlue brain
Blue brain
baabtra.com - No. 1 supplier of quality freshers
 
5g
5g5g
5g
baabtra.com - No. 1 supplier of quality freshers
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
baabtra.com - No. 1 supplier of quality freshers
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra soft skills
Baabtra soft skillsBaabtra soft skills
Baabtra soft skills
baabtra.com - No. 1 supplier of quality freshers
 
Cell phone jammer
Cell phone jammerCell phone jammer
Cell phone jammer
baabtra.com - No. 1 supplier of quality freshers
 

Recently uploaded (20)

How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Studying Drama: Definition, types and elements
Studying Drama: Definition, types and elementsStudying Drama: Definition, types and elements
Studying Drama: Definition, types and elements
AbdelFattahAdel2
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Studying Drama: Definition, types and elements
Studying Drama: Definition, types and elementsStudying Drama: Definition, types and elements
Studying Drama: Definition, types and elements
AbdelFattahAdel2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 

Php sessions & cookies

  • 3. What you Benefit ??? By the end of this session you will learn ● How to use Sessions and Cookies to maintain the state among multiple requests.
  • 4. TASK OF THE DAY Create a session when a user log in to his account. When user logout from his account the session should expire LOGIN PAGE
  • 5. INTRODUCTION TO PHP SESSIONS AND COOKIES
  • 6. Introduction To PHP Sessions And Cookies We had already tried passing data to a server . But..how the server knows the user from which the requests are received…?
  • 8. Cookies •HTTP is a stateless protocol; this means that the web server does not know (or care) whether two requests comes from the same user or not; it just handles each request without regard to the context in which it happens. •Cookies are used to maintain the state in between requests—even when they occur at large time intervals from each other. •Cookies allow your applications to store a small amount of textual data (typically,4-6kB) on a Web client browser. •There are a number of possible uses for cookies, although their most common one is maintaining state of a user
  • 9. Creating A Cookie • setcookie(“userid", "100", time() + 86400); • This simply sets a cookie variable named “userid” with value “100” and this variable value will be available till next 86400 seconds from current time Cookie variable name variable value Expiration time.
  • 10. Accessing a Cookie • echo $_COOKIE[’userid’]; // prints 100 • Cookie as array – setcookie("test_cookie[0]", "foo"); – setcookie("test_cookie[1]", "bar"); – setcookie("test_cookie[2]", "bar"); – var_dump($_COOKIE[‘test_cookie’]);
  • 11. Destroying A Cookie •There is no special methods to destroy a cookie, We achieve it by setting the cookie time into a past time so that it destroys it – Eg : setcookie(‘userid’,100,time()-100);
  • 13. Sessions •Session serve the same purpose of cookies that is sessions are used to maintain the state in between requests •Session can be started in two ways in PHP – By changing the session.auto_start configuration setting in php.ini – Calling session_start() on the beginning of each pages wherever you use session(Most common way) Note: session_start() must be called before any output is sent to the browser
  • 14. Creating and accessing session • Once session is started you can create and access session variables like any other arrays in PHP – $_SESSION[‘userid’] = 100; – echo $_SESSION[‘userid’]; //prints 100 Session variable name variable value
  • 15. Destroying A Session •There are two methods to destroy a session variable 1. Using unset() function • Eg unset($_SESSION[‘userid’]) 1. Calling session_destroy() method. This will effectively destroy all the session variables. So for deleting only one variable you should go for the previous method • Session_destroy()
  • 16. Let’s try implementing with our task
  • 17. Step 1 Goto Login_baabtra.php page and set form action to Profile.php page <form name=”login” action=”login_action.php” method=”post”>
  • 18. Step 2 Login_action.php Page Create database connection here mysql_connect('localhost','root',''); mysql_select_db("Baabtra"); $result=mysql_query("select * from tbl_user where vchr_user_name='$username'and vchr_password='$password'");
  • 19. Step 3 Login_action.php Page Check whether id is valid or not.if valid user then create session if(mysql_num_rows($result)){ while($row=mysql_fetch_array($result)){ session_start(); $_SESSION['user_id']=$row['pk_int_user_id']; header(‘Location: profile.php’); } } checks whether there is any resultant
  • 20. Step 3 Login_action.php Page Check whether id is valid or not.if valid user then create session if(mysql_num_rows($result)){ while($row=mysql_fetch_array($result)){ session_start(); $_SESSION['user_id']=$row['pk_int_user_id']; header(‘Location: profile.php’); } } starts a session
  • 21. Step 3 Login_action.php Page Check whether id is valid or not.if valid user then create session if(mysql_num_rows($result)){ while($row=mysql_fetch_array($result)){ session_start(); $_SESSION['user_id']=$row['pk_int_user_id']; header(‘Location: profile.php’); } } sets a session variable userid with value of pk_int_user_id field of the resultant set
  • 22. Step 3 Login_action.php Page Check whether id is valid or not.if valid user then create session if(mysql_num_rows($result)){ while($row=mysql_fetch_array($result)){ session_start(); $_SESSION['user_id']=$row['pk_int_user_id']; header(‘Location: profile.php’); } } sets a session variable userid with value of pk_int_user_id field of the resultant set
  • 23. Step 3 Login_action.php Page Check whether id is valid or not.if valid user then create session if(mysql_num_rows($result)){ while($row=mysql_fetch_array($result)){ session_start(); $_SESSION['user_id']=$row['pk_int_user_id']; header(‘Location: profile.php’); } } sets a session variable userid with value of pk_int_user_id field of the resultant set
  • 24. Step 3 Login_action.php Page Check whether id is valid or not.if valid user then create session if(mysql_num_rows($result)){ while($row=mysql_fetch_array($result)){ session_start(); $_SESSION['user_id']=$row['pk_int_user_id']; header(‘Location: profile.php’); } } header function is used for page redirection
  • 25. Step 4 Design a profile Page and Create a link for Logout
  • 26. Step 5 Go to profile page and display Qualification details of that particular user using session variable.
  • 27. Step 5 Profile.php session_start(); $user_id=$_SESSION['user_id']; mysql_connect('localhost','root',''); mysql_select_db("Baabtra"); $result=mysql_query("select * from tbl_academic_qualificaion where fk_int_user_id='$user_id'"); echo “ qualification name-----college--------percentage--------passout”; while($data=mysql_fetch_assoc($result)){ echo $data['vchr_qualification_name']; echo $data['vchr_qualification_name']; echo $data['int_percentage']; echo $data['dat_passout_date']; }
  • 28. Step 5 Profile.php session_start(); $user_id=$_SESSION['user_id']; mysql_connect('localhost','root',''); mysql_select_db("Baabtra"); $result=mysql_query("select * from tbl_academic_qualificaion where fk_int_user_id='$user_id'"); echo “ qualification name-----college--------percentage--------passout”; while($data=mysql_fetch_assoc($result)){ echo $data['vchr_qualification_name']; echo $data['vchr_qualification_name']; echo $data['int_percentage']; echo $data['dat_passout_date']; } fetches the session variable user_id and stores to variable $userid
  • 29. Step 5 Profile.php session_start(); $user_id=$_SESSION['user_id']; mysql_connect('localhost','root',''); mysql_select_db("Baabtra"); $result=mysql_query("select * from tbl_academic_qualificaion where fk_int_user_id='$user_id'"); echo “ qualification name-----college--------percentage--------passout”; while($data=mysql_fetch_assoc($result)){ echo $data['vchr_qualification_name']; echo $data['vchr_qualification_name']; echo $data['int_percentage']; echo $data['dat_passout_date']; } selects the qualification details of the user that matches with session value
  • 32. Comparison Cookies are stored in the user's browser A cookie can keep information in the user's browser until deleted by user or set as per the timer. It will not be destroyed even if you close the browser. Cookies can only store string We can save cookie for future reference Sessions are stored in server A session is available as long as the browser is opened. User cant disable the session. It will be destroyed if you close the browser Can store not only strings but also objects session cant be. Cookies Session
  • 33. END OF THE SESSION