Friday, 15 March 2013
0 comments

Cookies in php

Friday, March 15, 2013



  • What is a Cookie?
    A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

  • How to Create a Cookie?
    Syntax:
    setcookie(name, value, expire, path, domain);
    Example -
    setcookie("user", "Alex Porter", time()+3600);

  • How to Retrieve a Cookie Value?
    The PHP $_COOKIE variable is used to retrieve a cookie value.
    Example -
    // Print a cookie
    echo $_COOKIE["user"];
    // A way to view all cookies
    print_r($_COOKIE);

  • How to Delete a Cookie?
    When deleting a cookie you should assure that the expiration date is in the past.
    // set the expiration date to one hour ago
    setcookie("user", "", time()-3600);

    • Checking for Cookie Support from PHP


        < ? php
           if(!isset($_GET['testcookie']))
           {
             setcookie("testcookie", "test value");
             header("Location: {$_SERVER["PHP_SELF"]}?testcookie=1");
             exit;
           }
           else
           {
             if(isset($_COOKIE['testcookie']))
             {
               setcookie("testcookie");
               echo "You have cookies enabled";
             }
             else
             {
               echo "You do not support cookies!";
             }
           }
        ? >
    • Reading all cookie values


        < ? php
           foreach ($_COOKIE as $cookie_name => $cookie_value)
           {
             print "$cookie_name = $cookie_value
      ";
           }
        ? >
    • Still Logged In with cookie


        < ? php
           $auth = $_COOKIE['auth'];
           header( "Cache-Control:no-cache" );
           if( ! $auth == "ok" )
           {
             header("Location:login.php" );
             exit();
           }
        ? >
    • Printing a cookie value


         < ? php
           print 'Hello, ' . $_COOKIE['userid'];
         ?>
    • Reading a cookie value


        < ? php
          if (isset($_COOKIE['flavor']))
          {
             print "You ate a {$_COOKIE['flavor']} cookie.";
          }
        ?>      

0 comments:

Post a Comment

SUBSCRIBE VIA EMAIL

 
Toggle Footer
Top