Thursday, September 15, 2011

demo code to test third party cookie

Hi Folks,

Here i am sharing code snippets that i use to test and understand cookie. Specially third party cookie.

What i did ?
Actually i create two sub domains www.local-dom1.com and www.local-dom2.com.
then i tried set cookie across domains.

How i did it ?
I wrote php code which set cookie and then convert out header as image with content. and then use IMG html tag with src that PHP script.

PHP code:


<?php

/* The next four values may be changed. */
$CookieName = "mycookie";    // Cookie's name
$CookieValue = "hello Ravi"; // Cookie's value
$CookieDirectory = "/";        // Cookie directory ("/" for all directories)
$DaysCookieShallLast = 31;     // Days before expiration (decimal number okay.)
/*********************************************************************/
$CookieDomain = 'www.local-dom1.com';
$lasting = ($DaysCookieShallLast<=0) ? "" : time()+($DaysCookieShallLast*24*60*60);
setcookie($CookieName,$CookieValue,$lasting,$CookieDirectory,$CookieDomain);
$image = "R0lGODlhBQAFAJH/AP///wAAAMDAwAAAACH5BAEAAAIALAAAAAAFAAUAAAIElI+pWAA7n";
header('Content-type: image/gif');
echo base64_decode($image);
exit;
?>

HTML Code at local-demo2.com:


<img
   src="http://www.local-dom1.com/public/setcookie.php"
   width="1"
   height="1"
   border="0"
   alt="cookie">
<script>

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^s+|s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
alert(getCookie('mycookie'));
</script>
<?php echo $_COOKIE["mycookie"]; ?>

Hope code will be helpful to understand what i said in my previous post.

Happy coding !!!

No comments:

Post a Comment