Docstoc

HTML

Document Sample
HTML Powered By Docstoc
					  SQL & PHP

Cookies & Sessions
  Shopping Carts
            Cookies & Sessions
 Cookies
   Name-value pair associated w/ website
   Stored on client
   Once set
      Included in all future page requests to site
         Until browser is closed or it expires
             Cookies & Sessions
 Life Cycle of a PHP-generated Cookie
   Browser requests a URL corresponding to a PHP script
      Call to the setcookie() function built into PHP
   PHP-generated page sent back to browser
      HTTP set-cookie header containing name & value of cookie
   Browser receives HTTP header
      Stores specified value as a cookie
   Subsequent page requests to website will contain:
      HTTP cookie header
         Sends the name/value pair to the script requested
   Upon receipt of a page request with a cookie header
      PHP creates an entry in the $_COOKIE array
          Cookie’s name & value
                    Cookies & Sessions
 Cookies
   setcookie() function adds headers to a page
        Must be called before any page content is sent
   Using the setcookie() function
   setcookie(name [, value[, expiryTime[, path[, domain[, secure[, httpOnly ] ] ] ] ] ] )
               Cookies & Sessions
 Cookies
   Using the setcookie() function
    setcookie(name [, value[, expiryTime[, path[, domain[, secure[, httpOnly ] ] ] ] ] ]
    )
      name  Only required parameter
      value  allows ou to create a new cookie/ modify a cookie
      expiryTime  specify the time to delete cookie (from number of
       seconds from Jan 1, 1970)
           Current time in this format is obtained using PHP’s time function
           time() + 3600  cookie will expire in an hour
      path  restricts the cookie’s access to a given path on server
      domain  restricts the cookie’s access to a given domain
           Cookies will be returned only to the host from which it was originally
            sent
           For www.example.com & support.example.com  ‘.example.com’
      secure  indicates cookie should be sent only w/page requests over a
       secure (SSL) connection (1 or 0)
      httpOnly  tells the browser to prevent JavaScript code (on site) from
                                  Cookies & Sessions
         Cookies
               Example
// assume file name is index.php                    <!– assume file name is welcome.html.php -->
                                                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
// checks if $_COOKIE[„visits‟ is set               <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en”>
if (!isset($_COOKIE[„visits‟]))                     <head>
{
  $_COOKIE[„visits‟] = 0;                            <title> Page Title </title>
}                                                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
$visits = $_COOKIE[„visits‟] + 1;                   />
setcookie(„visits‟, $visits, time() + 3600 * 24 *
365); // visits cookie will reflect # of visits     </head>
                                                    <body>
Include „welcome.html.php‟;                           <?php
                                                        if ($visits >1)
?>                                                      {
                                                           echo “This is visit number $visits.”;
                                                        }
                                                        else
                                                        {
                                                           // First visit
                                                           echo „Welcome to my website! Click here for a tour!;
                                                        }
                                                      ?>
                                                    </body>
                                                    </html>
             Cookies & Sessions
 Cookies
   Are inappropriate for storing large amounts of info
      Not used in e-commerce sites for storing shopping cart items
   Be aware that browsers will:
      Limit the number & size allowed per site
      Some start deleting old cookies after 20 have been set
      Some will allow up to 50 cookies
          New cookies beyond this limit will be rejected
      Enforce a maximum combined size for all cookies from all sites
   PHP sessions were developed as a solution
             Cookies & Sessions
 PHP Sessions
   Store data on the server
      A single cookie containing the user’s session ID is stored on
       client
          Identifies user uniquely for the duration of their visit
          Sent back to server on every subsequent request
   Before using, make sure:
      Inside your php.ini file:
    session.save_handler          = files
    session.save_path             = “C:\WINDOWS\TEMP”
    session.use_cookies           =1
             Cookies & Sessions
 PHP Sessions
   session_start()
      Looks for a session ID or starts a new session
      Must come before any page content is sent to browser
      To create session variable, set a value in the $_SESSION array
          $_SESSION*‘name’+ = ‘value’;
      To remove a variable from current session, PHP’s unset ()
          Unset ($_SESSION*‘name’+);
      To end the current session & delete all registered variables, you
       can clear all stored values & use session_destroy()
       $_SESSION = array();
       session_destroy();
             Cookies & Sessions
 A Simple Shopping Cart
   Example:
      Controller script (index.php) feeding two templates:
          A product catalog (catalog.html.php)
          A checkout page (cart.html.php)
              Order could be submitted to a processing system to handle details
                of payment & shipping (PayPal)
                 Cookies & Sessions
 A Simple Shopping Cart
   Controller script (index.php) feeding two templates:
      List description & price per item
      Store list of items user placed in shopping cart in an array
            Stored using PHP sessions
     <?
     include_once $_SERVER[„DOCUMENT_ROOT‟] . „/includes/magicquotes.inc.php‟;

     $items = array(
       array („id‟ => „1‟, „desc‟ => „canadian-Australian Dictionary‟, „price‟ => 24.95),
       array („id‟ => „2‟, „desc‟ => „As-new parachute (never opened)‟, „price‟ => 1000.00),
       array („id‟ => „3‟, „desc‟ => „Songs of the Goldfish (2CD set)‟, „price‟ => 19.99),
       array („id‟ => „4‟, „desc‟ => „Simply Javascript (SitePoint)‟, „price‟ => 39.95));

     session_start();
     if (!isset($_SESSION[„cart‟]))
     {
        $_SESSION[„cart‟] = array();       // „cart‟ initialized to an empty array = empty cart
     }

     //handle selections…

     include „catalog.html.php‟;
                    Cookies & Sessions
 A Simple Shopping Cart
   Catalog.html.php
   <?php include_once $_SERVER[„DOCUMENT_ROOT‟] . „/includes/helpers.inc.php‟; ?>
   <!DOCTYPE ……..>
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en”>
   <head>
    <title> Page Title </title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   </head>
   <body>

   <!-- count() outputs the number of items in the aray stored in the $_SESSION[„cart‟] -->
     <p> Your shopping cart contains <?php echo count ($_SESSION[„cart‟]); ?> items.</p>


   <!-- link to let the user view contents of the shopping cart (Proceed to Chekout) -->
     <p><a href=“?cart”>View your cart</a></p>

    <table border=“1”>
    <thead>
     <tr>
      <th> Item Description </th>
      <th> Price </th>
     </tr>
    </thead>
                   Cookies & Sessions
 A Simple Shopping Cart
   Catalog.html.php
    <tbody>
    <?php foreach ($items as $item): ?>
    <tr>
     <td><?php htmlout($item[„desc‟]); ?></td>

   <!-- number_format() to display prices with two digits after decimal point -->
       <td>$<?php echo number_format($item[„price‟], 2); ?></td>

     <td>

   <!– for each item, a form with a Buy button that submits the unique ID of the item -->
        <form action=“” method=“post”>
          <div>
            <input type=“hidden” name=“id” value=“<?php htmlout($item[„id‟]); ?>” />
            <input type=“submit” name=“action” value=“Buy” />
          </div>
        </form>
       </td></tr> <?php endforeach; ?>
     </tbody>
     </table>
   <p> All prices are imaginary.</p>
   </body>
   </html>
                    Cookies & Sessions
 A Simple Shopping Cart
   Controller script (index.php)
   <?
   include_once $_SERVER[„DOCUMENT_ROOT‟] . „/includes/magicquotes.inc.php‟;
   $items = array(
     array („id‟ => „1‟, „desc‟ => „canadian-Australian Dictionary‟, „price‟ => 24.95),
     array („id‟ => „2‟, „desc‟ => „As-new parachute (never opened)‟, „price‟ => 1000.00),
     array („id‟ => „3‟, „desc‟ => „Songs of the Goldfish (2CD set)‟, „price‟ => 19.99),
     array („id‟ => „4‟, „desc‟ => „Simply Javascript (SitePoint)‟, „price‟ => 39.95));

   session_start();
   if (!isset($_SESSION[„cart‟]))
   {
      $_SESSION[„cart‟] = array();       // „cart‟ initialized to an empty array = empty cart
   }

   //controller will receive a form submission with $_POST[‘action’]) set to ‘Buy’
   if (isset($_POST[„action‟]) and $_POST[„action‟] == „Buy‟)
   {
     //Add item to the end of the $_SESSION[‘cart’] array
     $_SESSION[„cart‟] [] = $_POST[„id‟];
     header(„Location: .‟); // browser is redirected to the same page without a query string
     exit();                // to prevent an item being added to the cart by refreshing the page
   }
                       Cookies & Sessions
 A Simple Shopping Cart
      Controller script (index.php)
If (isset($_GET[„cart‟])) // controller receives a request to view cart with $_GET[‘cart’] array set
{
  $cart = array();
  $total = 0;
  foreach ($_SESSION[„cart‟] as $id) // $cart array built to reflect items user has added to shopping cart
  {
    foreach ($items as $product)
    {
      if ($product [„id‟] ==$id)
       {
        $cart[] = $poduct;
        $total += $product[„price‟];
        break;       // this command tells PHP to stop executing second foreach loop, product found
       }
     }
   }
      include „cart.html.php;
      exit();
}

include „catalog.html.php‟;

?>
                     Cookies & Sessions
 A Simple Shopping Cart
    Cart.html.php
  <?php include_once $_SERVER[„DOCUMENT_ROOT‟] . „/includes/helpers.inc.php‟; ?>
  <!DOCTYPE ……..>
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en”>
  <head>
   <title> Page Title </title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>

  <p> Your shopping cart.</p>
  <?php if (count($cart) > 0); ?>

    <table border=“1”>
    <thead>
      <tr>
      <th> Item Description </th>
      <th> Price </th>
      </tr>
     </thead>
  <tfoot>
   <tr>
    <td> Total:</td>
    <td>$<?php echo number_format($total, 2); ?></td>
    </tr>
  </tfoot>
                   Cookies & Sessions
 A Simple Shopping Cart
   Cart.html.php
    <tbody>
    <?php foreach ($cart as $item): ?>
    <tr>
     <td><?php htmlout($item[„desc‟]); ?></td>

   <!-- number_format() to display prices with two digits after decimal point -->
       <td>$<?php echo number_format($item[„price‟], 2); ?></td>
        </td>
       </tr>
    <?php endforeach; ?>
     </tbody>
   </table>
    <?php else: ?>
    <p> Your cart is empty! </p>
    <?php endif ?>
         <form action=“?” method=“post”>
           <p>
             <a href=“?”>continue Shopping</a> or
             <input type=“submit” name=“action” value=“empty cart” />
           </p>
         </form>
   </body>
   </html>
                    Cookies & Sessions
 A Simple Shopping Cart
   Controller script (index.php) – Empty Cart
   <?
   include_once $_SERVER[„DOCUMENT_ROOT‟] . „/includes/magicquotes.inc.php‟;
   $items = array(
     array („id‟ => „1‟, „desc‟ => „canadian-Australian Dictionary‟, „price‟ => 24.95),
     array („id‟ => „2‟, „desc‟ => „As-new parachute (never opened)‟, „price‟ => 1000.00),
     array („id‟ => „3‟, „desc‟ => „Songs of the Goldfish (2CD set)‟, „price‟ => 19.99),
     array („id‟ => „4‟, „desc‟ => „Simply Javascript (SitePoint)‟, „price‟ => 39.95));

   session_start();
   if (!isset($_SESSION[„cart‟]))
   {
      $_SESSION[„cart‟] = array();       // „cart‟ initialized to an empty array = empty cart
   }

   //controller will receive a form submission with $_POST[‘action’]) set to ‘Buy’
   if (isset($_POST[„action‟]) and $_POST[„action‟] == „Buy‟)
   {
     //Add item to the end of the $_SESSION[‘cart’] array
     $_SESSION[„cart‟] [] = $_POST[„id‟];
     header(„Location: .‟); // browser is redirected to the same page without a query string
     exit();                // to prevent an item being added to the cart by refreshing the page
   }
                     Cookies & Sessions
 A Simple Shopping Cart
     Controller script (index.php)
if (isset($_POST[‘action’]) and $_POST[‘action’] == ‘empty cart’)
{
  // empty the $_SESSION[‘cart’] array
  unset($_SESSION[‘cart’]); // since all we want is to empty the cart, we just unset the session
  header(‘Location: ?cart’); // using destroy would have deleted the session itself
  exit();
}
if (isset($_GET[„cart‟])) // controller receives a request to view cart with $_GET[‘cart’] array set
{
  $cart = array();
  $total = 0;
  foreach ($_SESSION[„cart‟] as $id) // $cart array built to reflect items user has added to shopping cart
  {
    foreach ($items as $product)
    {
      if ($product [„id‟] ==$id)
       {
        $cart[] = $poduct;
        $total += $product[„price‟];
        break;       // this command tells PHP to stop executing second foreach loop, product found
       }
     }
   }
                       Cookies & Sessions
 A Simple Shopping Cart
      Controller script (index.php)
include „cart.html.php‟;
    exit();
}

include „catalog.html.php‟;

?>

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:53
posted:4/16/2011
language:Czech
pages:21