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>

PHP SESSIONS & COOKIE.pptx

  • 1.
    PHPSESSIONS Prepared By-Mrs.ShitalV. Ghotekar AssistantProfessor MAEER’S MIT Art’s,Commerce & Science College,Alandi(D),Pune
  • 2.
    ServerSide State Management  PHP providesfor 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. ClientSide 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 sessionis 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 sessioncreates 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 $_SESSIONis 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 “UserName =“. $_SESSION[‘username’]; echo “User Id=“. $_SESSION[‘userid’]; ?> Output- User Name=Sonal User Id=1
  • 10.
    Update Session Variable in PHP  Toupdate 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  // removeall session variables session_unset();  // destroy the session variables session_destroy();
  • 12.
    Destroy a Session inPHP  <?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 aPHP 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 isa 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.Tostore 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  Thereare 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 inPHP  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 inPHP 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 // setthe 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 Toupdate 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 inPHP  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  SelfProcessing 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 oftwo 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>