• Set/Get Cookie using PHP and JavaScript


    Find variety of codes and details discussion about the cookie both using JavaScript and PHP:
    1. Set cookie through PHP and get through JavaScript
    2. Set cookie through JavaScript and get through PHP
    3. Set cookie in JavaScript and get through JavaScript
    4. Set cookie through PHP and get through PHP
    5. Set the Array Cookies
    6. Delete all Cookies through PHP
    Commented code are left so that you can find something new or play with that.

    1. Set cookie through PHP and get through JavaScript

    <?php
    //Page: set_cookie.php
    //$_SERVER['HTTP_HOST'] = 'http://www.example.com ';
    // localhost create problem on IE so this line
    // to get the top level domain
    $myDomain = ereg_replace("^[^.]*.([^.]*).(.*)$", '1.2', $_SERVER['HTTP_HOST']);
    $setDomain = ($_SERVER['HTTP_HOST']) != "localhost" ? ".$myDomain" : false;
    setcookie ("site", 'http://only-your-views.blogspot.com', time()+3600*24*(2), '/', "$setDomain", 0 );
    // You can change (2) to any negative value (-2) for deleting it. It is number of days for cookie to keep live. Any -ve number will tell browser that it is useless now.
    ?>
    (In ereg_replace, double quote is not required but for some reason it was not visible on page. So used double quite.)
    Page: get_cookie.html
    <script>
    function readCookie(name) {
     var cookiename = name + "=";
     var ca = document.cookie.split(';');
     for(var i=0;i < ca.length;i++)
     {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(cookiename) == 0) return c.substring(cookiename.length,c.length);
     }
     return null;
    }
    document.write("n" + readCookie('site'));
    </script>

    2. Set cookie through JavaScript and get through PHP

    Page: set_cookie.html
    <script>
    document.cookie = 'name=David' ;
    </script>
    Page: get_cookie.php
    <?php
    var_dump($_COOKIE['name']);
    ?>

    3. Set cookie through JavaScript and get through JavaScript

    <script type="text/javascript">
    days = 3; // -ve for deleting it.
    var date = new Date();
    date.setTime(date.getTime ()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    document.cookie = 'language=ruby' + expires;
    function readCookie(name)
    {
     var cookiename = name + "=";
     var ca = document.cookie.split(';');
     for(var i=0;i < ca.length;i++)
     {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(cookiename) == 0) return c.substring(cookiename.length,c.length);
     }
     return null;
    }
    // refresh the page for getting the value or use this line in another page
    document.write("n" + readCookie('language'));
    </script>

    4. Set cookie through PHP and get through PHP

    <?php
    //$_SERVER['HTTP_HOST'] = 'http://www.example.com ';
    // localhost create problem on IE so this line
    // to get the top level domain
    $myDomain = ereg_replace('^[^.]*.([^.]*).(.*), '1.2', $_SERVER['HTTP_HOST']);
    $setDomain = ($_SERVER['HTTP_HOST']) != "localhost" ? ".$myDomain" : false;
    setcookie ("site2", 'http://only-your-views.blogspot.com', time()+3600*24*(2), '/', "$setDomain", 0 );
    echo @$_COOKIE ['site2'];
    ?>

    5. Set the Array Cookies

    <?php
    setcookie("cookie1[0]", "cookiethree");
    setcookie("cookie1[1]", "cookietwo");
    setcookie("cookie1[2]", "cookieone");
    // after the page reloads, echo them out
    if (isset($_COOKIE['cookie1']))
    {
     foreach ($_COOKIE['cookie1'] as $name => $value)
     {
      echo "cookie1[$name] : $value <br />n";
     }
    }
    ?>

    6. Delete all Cookies through PHP

    <?php
    foreach ($_COOKIE as $k=>$v)
    {
     if (is_array($_COOKIE[$k]))
     {
      foreach ($_COOKIE[$k] as $key=>$val)
      {
       setcookie($k.'['.$key.']',"", time()+3600*24*(-100));
      }
     }
     setcookie($k,"", time()+3600*24*(-100));
    }
    ?>

    Few facts about Cookie:

    Expire time is dependent of Client time. So, remember to check your geo location and your visitors geo location.
    If you do not specify expiry date for cookie then it will available, until browser is closed.
    Path for cookie is the current directory by default.
    In PHP, cookie must be sent before any output to client.
    In PHP setcookie function accepts argument like this:
    True/False Setcookie (name, value, expire, path, domain, secure)
    Path = ‘/’ will set cookie for entire domain. Path = ‘foo’ will set it for foo directory and subdirectory of ‘/foo/’.
    Httponly is last parameter added in PHP 5.2.0 in setcookie (), but not supported by all browsers.
    For deleting cookie, you will set cookie again but with days with negative values.

  • 0 comments:

    Post a Comment

    FAVOURITE LINE

    To steal ideas from one is plagiarism. To steal from many is Research.

    ADDRESS

    Mumbai , Maharashtra

    EMAIL

    shikha.pathak6@gmail.com
    shikha.the.swt.pari@gmail.com

    Skype

    shikha_pari