SlideShare a Scribd company logo
1 of 26
PHPSESSIONS
Prepared By-Mrs.ShitalV. Ghotekar
Assistant Professor
MAEER’S MIT Art’s,Commerce & Science College,Alandi(D),Pune
ServerSide
State
Management
 PHP provides for two different techniques for state management
of your web application, they are:
 1. Server Side State Management
 In server side state management we store user specific
information required to identify the user on the server. And this
information is available on every webpage.
 In PHP we have Sessions for server side state management.
 PHP session variable is used to store user session information like
username, user id etc. and the same can be retrieved by accessing
the session variable on any webpage of the web application until
the session variable is destroyed.
ClientSide
Server
Management
 2. Client Side State Management
 Client side state management the user specific information is
stored at the client side i.e. in the bowser.
 Again, this information is available on all the webpages of the web
application.
 In PHP we have Cookies for client side state management.
 Cookies are saved in the browser with some data and expiry
date(till when the cookie is valid).
 One drawback of using cookie for state management is the user
can easily access the cookie stored in their browser and can even
delete it.
Sessions
 A session is a way to store information (in variables) to be
used across multiple pages.
 Session variables are storing user information to be used
across multiple pages (e.g. username, favorite color).
 By default, session variables last until the user closes the
browser.
 Session variables hold information about one single user, and
are available to all pages in one application.
Sessions
 PHP session creates unique user id for each browser to
recognize the user and avoid conflict between multiple
browsers.
Start a PHP
Session
 A session is started with the session_start() function.
 Note:
 The session_start() function must be the very first thing in your
document. Before any HTML tags.
PHP
$_SESSION
 PHP $_SESSION is an associative array that contains all session
variables.
 It is used to set and get session variable values.
 Program 1-
 <?php
 session_start();
 $_SESSION[‘username']='Sonal’;
 echo “User Name=“.$_SESSION[‘username'];
 ?>
 Output- User Name=Sonal
PHP
$_SESSION
 Program 2- session1.php
 <?php
 session_start();
 $_SESSION[‘username']='Sonal’;
 $_SESSION[‘userid’]=1;
 ?>
 <html>
 <a href="session2.php">Visit next page</a>
 </html>

PHP
$_SESSION
 Session2.php
<?php
session_start();
echo “User Name =“. $_SESSION[‘username’];
echo “User Id=“. $_SESSION[‘userid’];
?>
Output-
User Name=Sonal
User Id=1
Update
Session
Variable in
PHP
 To update any value stored in the session variable, start the session by calling session_start()
function and then simply overwrite the value to update session variable.
 <?php
 // start the session
 session_start ();
 // update the session variable values
 $_SESSION [“userid"] = "1111";
 ?>
 <html>
 <body>
 <?php
 echo “User Name is: ".$username."<br/>";
 echo “User Id is: ".$userid;
 ?>
 </body>
 </html>
 User Name is: Sonal
 User Id is: 1111
 We just updated the value of userid in the session variable from 1 to 1111
PHP
Destroying
Session
 // remove all session variables
session_unset();
 // destroy the session variables
session_destroy();
Destroy a
Session in PHP
 <?php
 // start the session
 session_start ();
 ?>
 <html>
 <body>
 <?php
 // clean the session variable
 session_unset ();
 // destroy the session
 session_destroy ();
 ?>
 </body>
 </html>
SETA
 1.Write a PHP script to keep track of number of times the web page
has been access. [Use session and cookies]
 <html>
<head>
<title> Number of times the web page has been visited. </title>
</head>
<body>
<?php
session_start();
if(isset($_SESSION['count']))
$_SESSION['count']=$_SESSION['count']+1;
else
$_SESSION['count']=1;
echo "This page is accessed " .$_SESSION['count'] ." times";
?>
 OUTPUT- This page is accessed 2 times
PHPCookies
 Cookie is a small piece of information stored as a file in the user's
browser by the web server.
 Once created, cookie is sent to the web server as header
information with every HTTP request.
 User can use cookie to save any data but it should not exceed
1K(1024 bytes) in size
Real worldUse
ofCookies
 1.To store user information like when he/she visited, what pages
were visited on the website etc., so that next time the user visits
your website you can provide a better user experience.
 2.You can use cookies to store number of visits or view counter.
Types of
Cookies
 There are two types of cookies :
 1. Session Cookie: This type of cookies are temporary and are
expire as soon as the session ends or the browser is closed.
 2. Persistent Cookie: To make a cookie persistent we must
provide it with an expiration time.Then the cookie will only expire
after the given expiration time, until then it will be a valid cookie.
Creating a
Cookie in PHP
 In PHP user can create/set a cookie using the setcookie() function.
 syntax : setcookie(name, value, expire, path, domain, secure);
 The first argument which defines the name of the cookie is
mandatory, rest all are optional arguments.
Creating a
Cookie in PHP
setcookie(name,
value, expire, path,
domain, secure);
Example 1-
 Example-
 <?php
 // cookie will expire when the browser close
 Setcookie(“username”,”anushree”);
 // cookie will expire in 1 hour
 Setcookie(“username”,”anushree”,time()+3600);
?>
To access a stored cookie we use the $_COOKIE global variable, and
can use the isset() method to check whether the cookie is set or not.
Example 2-
<?php
// set the cookie for 1 Day / 24 Hrs
setcookie ("username", “anushree", time()+3600*24);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
Updating
Cookie in PHP
To update the value of username cookie from anushree to anu
<?php
// set the cookie for 1 Day
setcookie ("username", “anu", time()+3600*24);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
Delete a
Cookie in PHP
 To delete/remove a cookie, we need to expire the cookie, which
can be done by updating the cookie using the setcookie() function
with expiration date in past.
 <?php
 // updating the cookie
 setcookie("username", “anu", time() - 3600);
 ?>
 <html>
 <body>
 <?php
 echo "cookie username is deleted!";
 ?>
 </body>
 </html>
Self Processing
Forms
 Self Processing Forms-One PHP page can be used to both generate a
form and process it.
 Syntax-
 <form action=“<?php echo $_SERVER[‘PHP_SELF’]?>” method=“POST”>
 It sends the submitted form data to the page itself, instead of jumping to
the different page.
Self Processing
Form-Example
 <html>
 <head>
 <title> SELF PROCESSING FORM </title>
 </head>
 <body>
 <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="GET">
 <center> Simple Calculator for Addition<br>
 <b>Enter the first number</b> <input type="text" name="num1"><br>
 <b>Enter the second number</b> <input type="text" name="num2"><br>
 <input type="submit" name="add" value="Addition">
 </form>
 <?php
 if($_GET['add']=="Addition")
 $num1=$_GET['num1'];
 $num2=$_GET['num2'];
 $add=$num1+$num2;
 echo "<br> <input type=text value=$add>";
 ?>
 </body>
 </html>
Sticky Form
 <html>
 <head>
 <title> STICKY FORM </title>
 </head>
 <body>
 <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="GET">
 <center> Simple Calculator for Addition<br>
 <b>Enter the first number</b> <input type="text" name="num1" value="<?php echo
$_GET['num1']?>"><br>
 <b>Enter the second number</b> <input type="text" name="num2" value="<?php echo
$_GET['num2']?>"><br>
 <input type="submit" name="add" value="Addition">
 </form>
 <?php
 if($_GET['add']=="Addition")
 $num1=$_GET['num1'];
 $num2=$_GET['num2'];
 $add=$num1+$num2;
 echo "<br> <input type=text value=$add>";
 ?>
 </body>
Example of
Sticky form
for
comparison
of two string
 <html>
 <head>
 <title> sticky </title>
 </head>
 <form action =“sticky_comp.php" method="GET">
 Enter the first string <input type="text" name="t1" value="<?php echo $_GET['t1'] ?>"> <br>
 Enter the second string <input type="text" name="t2" value="<?php echo $_GET['t2'] ?>"> <br>
 <input type="submit" name="ok" value="ok">
 </form>
 <body>
 <?php
 $s1=$_GET['t1'];
 $s2=$_GET['t2'];
 if(isset($_GET['ok']))
 //if(!is_null($s1) && !is_null($s2))
 {
 if($s1==$s2)
 {
 echo "Strings are equal";
 }
 else
 {
 echo "Strings are not equal";
 }
 }
 ?>
 </body> </html>

More Related Content

Similar to PHP SESSIONS & COOKIE.pptx

Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In PhpHarit Kothari
 
lecture 13.pptx
lecture 13.pptxlecture 13.pptx
lecture 13.pptxITNet
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingAhmed Swilam
 
Parameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPParameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPamichoksi
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
Php - Getting good with session
Php - Getting good with sessionPhp - Getting good with session
Php - Getting good with sessionFirdaus Adib
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionssalissal
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptxITNet
 
PHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web DevelopmentPHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web DevelopmentEdureka!
 

Similar to PHP SESSIONS & COOKIE.pptx (20)

4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In Php
 
Php session
Php sessionPhp session
Php session
 
lecture 13.pptx
lecture 13.pptxlecture 13.pptx
lecture 13.pptx
 
Sessions in php
Sessions in php Sessions in php
Sessions in php
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
PHP 2
PHP 2PHP 2
PHP 2
 
Parameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPParameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHP
 
Php
PhpPhp
Php
 
Php BASIC
Php BASICPhp BASIC
Php BASIC
 
session.ppt
session.pptsession.ppt
session.ppt
 
18.register login
18.register login18.register login
18.register login
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
Ph
PhPh
Ph
 
Php - Getting good with session
Php - Getting good with sessionPhp - Getting good with session
Php - Getting good with session
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
FP512 Cookies sessions
FP512 Cookies sessionsFP512 Cookies sessions
FP512 Cookies sessions
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
PHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web DevelopmentPHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web Development
 

Recently uploaded

STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxSTOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxMurugaveni B
 
Recombinant DNA technology( Transgenic plant and animal)
Recombinant DNA technology( Transgenic plant and animal)Recombinant DNA technology( Transgenic plant and animal)
Recombinant DNA technology( Transgenic plant and animal)DHURKADEVIBASKAR
 
OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024innovationoecd
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRlizamodels9
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfSELF-EXPLANATORY
 
Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024AyushiRastogi48
 
zoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzohaibmir069
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Neurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trNeurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trssuser06f238
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real timeSatoshi NAKAHIRA
 
Scheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxScheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxyaramohamed343013
 
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxRESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxFarihaAbdulRasheed
 
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...lizamodels9
 
Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫qfactory1
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)riyaescorts54
 
Forest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantForest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantadityabhardwaj282
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPirithiRaju
 

Recently uploaded (20)

STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxSTOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
 
Recombinant DNA technology( Transgenic plant and animal)
Recombinant DNA technology( Transgenic plant and animal)Recombinant DNA technology( Transgenic plant and animal)
Recombinant DNA technology( Transgenic plant and animal)
 
OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
 
Volatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -IVolatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -I
 
Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024
 
zoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistan
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
 
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort ServiceHot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
 
Neurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trNeurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 tr
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real time
 
Scheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxScheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docx
 
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxRESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
 
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
 
Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
 
Forest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantForest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are important
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdf
 

PHP SESSIONS & COOKIE.pptx

  • 1. PHPSESSIONS Prepared By-Mrs.ShitalV. Ghotekar Assistant Professor MAEER’S MIT Art’s,Commerce & Science College,Alandi(D),Pune
  • 2. ServerSide State Management  PHP provides for two different techniques for state management of your web application, they are:  1. Server Side State Management  In server side state management we store user specific information required to identify the user on the server. And this information is available on every webpage.  In PHP we have Sessions for server side state management.  PHP session variable is used to store user session information like username, user id etc. and the same can be retrieved by accessing the session variable on any webpage of the web application until the session variable is destroyed.
  • 3. ClientSide Server Management  2. Client Side State Management  Client side state management the user specific information is stored at the client side i.e. in the bowser.  Again, this information is available on all the webpages of the web application.  In PHP we have Cookies for client side state management.  Cookies are saved in the browser with some data and expiry date(till when the cookie is valid).  One drawback of using cookie for state management is the user can easily access the cookie stored in their browser and can even delete it.
  • 4. Sessions  A session is a way to store information (in variables) to be used across multiple pages.  Session variables are storing user information to be used across multiple pages (e.g. username, favorite color).  By default, session variables last until the user closes the browser.  Session variables hold information about one single user, and are available to all pages in one application.
  • 5. Sessions  PHP session creates unique user id for each browser to recognize the user and avoid conflict between multiple browsers.
  • 6. Start a PHP Session  A session is started with the session_start() function.  Note:  The session_start() function must be the very first thing in your document. Before any HTML tags.
  • 7. PHP $_SESSION  PHP $_SESSION is an associative array that contains all session variables.  It is used to set and get session variable values.  Program 1-  <?php  session_start();  $_SESSION[‘username']='Sonal’;  echo “User Name=“.$_SESSION[‘username'];  ?>  Output- User Name=Sonal
  • 8. PHP $_SESSION  Program 2- session1.php  <?php  session_start();  $_SESSION[‘username']='Sonal’;  $_SESSION[‘userid’]=1;  ?>  <html>  <a href="session2.php">Visit next page</a>  </html> 
  • 9. PHP $_SESSION  Session2.php <?php session_start(); echo “User Name =“. $_SESSION[‘username’]; echo “User Id=“. $_SESSION[‘userid’]; ?> Output- User Name=Sonal User Id=1
  • 10. Update Session Variable in PHP  To update any value stored in the session variable, start the session by calling session_start() function and then simply overwrite the value to update session variable.  <?php  // start the session  session_start ();  // update the session variable values  $_SESSION [“userid"] = "1111";  ?>  <html>  <body>  <?php  echo “User Name is: ".$username."<br/>";  echo “User Id is: ".$userid;  ?>  </body>  </html>  User Name is: Sonal  User Id is: 1111  We just updated the value of userid in the session variable from 1 to 1111
  • 11. PHP Destroying Session  // remove all session variables session_unset();  // destroy the session variables session_destroy();
  • 12. Destroy a Session in PHP  <?php  // start the session  session_start ();  ?>  <html>  <body>  <?php  // clean the session variable  session_unset ();  // destroy the session  session_destroy ();  ?>  </body>  </html>
  • 13. SETA  1.Write a PHP script to keep track of number of times the web page has been access. [Use session and cookies]  <html> <head> <title> Number of times the web page has been visited. </title> </head> <body> <?php session_start(); if(isset($_SESSION['count'])) $_SESSION['count']=$_SESSION['count']+1; else $_SESSION['count']=1; echo "This page is accessed " .$_SESSION['count'] ." times"; ?>  OUTPUT- This page is accessed 2 times
  • 14. PHPCookies  Cookie is a small piece of information stored as a file in the user's browser by the web server.  Once created, cookie is sent to the web server as header information with every HTTP request.  User can use cookie to save any data but it should not exceed 1K(1024 bytes) in size
  • 15. Real worldUse ofCookies  1.To store user information like when he/she visited, what pages were visited on the website etc., so that next time the user visits your website you can provide a better user experience.  2.You can use cookies to store number of visits or view counter.
  • 16. Types of Cookies  There are two types of cookies :  1. Session Cookie: This type of cookies are temporary and are expire as soon as the session ends or the browser is closed.  2. Persistent Cookie: To make a cookie persistent we must provide it with an expiration time.Then the cookie will only expire after the given expiration time, until then it will be a valid cookie.
  • 17. Creating a Cookie in PHP  In PHP user can create/set a cookie using the setcookie() function.  syntax : setcookie(name, value, expire, path, domain, secure);  The first argument which defines the name of the cookie is mandatory, rest all are optional arguments.
  • 18. Creating a Cookie in PHP setcookie(name, value, expire, path, domain, secure);
  • 19. Example 1-  Example-  <?php  // cookie will expire when the browser close  Setcookie(“username”,”anushree”);  // cookie will expire in 1 hour  Setcookie(“username”,”anushree”,time()+3600); ?> To access a stored cookie we use the $_COOKIE global variable, and can use the isset() method to check whether the cookie is set or not.
  • 20. Example 2- <?php // set the cookie for 1 Day / 24 Hrs setcookie ("username", “anushree", time()+3600*24); ?> <html> <body> <?php // check if the cookie exists if(isset($_COOKIE["username"])) { echo "Cookie set with value: ".$_COOKIE["username"]; } else { echo "cookie not set!"; } ?> </body> </html>
  • 21. Updating Cookie in PHP To update the value of username cookie from anushree to anu <?php // set the cookie for 1 Day setcookie ("username", “anu", time()+3600*24); ?> <html> <body> <?php // check if the cookie exists if(isset($_COOKIE["username"])) { echo "Cookie set with value: ".$_COOKIE["username"]; } else { echo "cookie not set!"; } ?> </body> </html>
  • 22. Delete a Cookie in PHP  To delete/remove a cookie, we need to expire the cookie, which can be done by updating the cookie using the setcookie() function with expiration date in past.  <?php  // updating the cookie  setcookie("username", “anu", time() - 3600);  ?>  <html>  <body>  <?php  echo "cookie username is deleted!";  ?>  </body>  </html>
  • 23. Self Processing Forms  Self Processing Forms-One PHP page can be used to both generate a form and process it.  Syntax-  <form action=“<?php echo $_SERVER[‘PHP_SELF’]?>” method=“POST”>  It sends the submitted form data to the page itself, instead of jumping to the different page.
  • 24. Self Processing Form-Example  <html>  <head>  <title> SELF PROCESSING FORM </title>  </head>  <body>  <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="GET">  <center> Simple Calculator for Addition<br>  <b>Enter the first number</b> <input type="text" name="num1"><br>  <b>Enter the second number</b> <input type="text" name="num2"><br>  <input type="submit" name="add" value="Addition">  </form>  <?php  if($_GET['add']=="Addition")  $num1=$_GET['num1'];  $num2=$_GET['num2'];  $add=$num1+$num2;  echo "<br> <input type=text value=$add>";  ?>  </body>  </html>
  • 25. Sticky Form  <html>  <head>  <title> STICKY FORM </title>  </head>  <body>  <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="GET">  <center> Simple Calculator for Addition<br>  <b>Enter the first number</b> <input type="text" name="num1" value="<?php echo $_GET['num1']?>"><br>  <b>Enter the second number</b> <input type="text" name="num2" value="<?php echo $_GET['num2']?>"><br>  <input type="submit" name="add" value="Addition">  </form>  <?php  if($_GET['add']=="Addition")  $num1=$_GET['num1'];  $num2=$_GET['num2'];  $add=$num1+$num2;  echo "<br> <input type=text value=$add>";  ?>  </body>
  • 26. Example of Sticky form for comparison of two string  <html>  <head>  <title> sticky </title>  </head>  <form action =“sticky_comp.php" method="GET">  Enter the first string <input type="text" name="t1" value="<?php echo $_GET['t1'] ?>"> <br>  Enter the second string <input type="text" name="t2" value="<?php echo $_GET['t2'] ?>"> <br>  <input type="submit" name="ok" value="ok">  </form>  <body>  <?php  $s1=$_GET['t1'];  $s2=$_GET['t2'];  if(isset($_GET['ok']))  //if(!is_null($s1) && !is_null($s2))  {  if($s1==$s2)  {  echo "Strings are equal";  }  else  {  echo "Strings are not equal";  }  }  ?>  </body> </html>