Php and Javascript Cookies

Set cookie through PHP and get through JavaScript



<?php
//Page: set_cookie.php
//$_SERVER['HTTP_HOST'] = 'http://www.webduos.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.
?>
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>
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']);
?>

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>
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'];
?>
Tags: Php Cookies, Cookies, Javascript, Javaceipt cookies

Comments

Popular posts from this blog

Create Desktop Application with PHP

Insert pandas dataframe into Mongodb

Add and delete columns dynamically in an HTML table