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.

  • # 1 - by lahlah

    It doesn’t work with me. :(All the javascript works fine, except for the set cookie part.When I check browser’s cookies for my blogger blog only the Google Analytics cookies are saved.

  • # 2 - by Satya Prakash Karan

    Are you setting the cookie correctly. Here in blogspot is a sub domain concept.

  • # 3 - by Satya Prakash Karan

    Are you setting the cookie correctly. Here in blogspot is a sub domain concept.

  • # 4 - by Deaddancer

    I have been grappling with a way to get a variable from javascript to PHP and finally gave cookies a try. I have a confirm pop up in my js, and based on what they click (OK/Cancel) I either set a cookie (load_all_data=Y) or I delete it. Then back in my PHP I do a comparison operation;
    (if ($_COOKIE[“load_all_data”]==’Y’)

    and it ALMOST works perfectly. The issue seems to be that when I process this PHP code, the cookie value is always one step behind, as if PHP reads the value of the cookie before it’s assigned. Does this make sense? Basically, my confirm message logic works flawlessly the 2nd time you click one of the options, but as soon as you change to the other option, it doesn’t work until you do it once more, and vice versa when switching back (i.e. OK vs. Cancel)

  • # 5 - by Deaddancer

    I have been grappling with a way to get a variable from javascript to PHP and finally gave cookies a try. I have a confirm pop up in my js, and based on what they click (OK/Cancel) I either set a cookie (load_all_data=Y) or I delete it. Then back in my PHP I do a comparison operation;(if ($_COOKIE[“load_all_data”]==’Y’) and it ALMOST works perfectly. The issue seems to be that when I process this PHP code, the cookie value is always one step behind, as if PHP reads the value of the cookie before it’s assigned. Does this make sense? Basically, my confirm message logic works flawlessly the 2nd time you click one of the options, but as soon as you change to the other option, it doesn’t work until you do it once more, and vice versa when switching back (i.e. OK vs. Cancel)

Comment pages
Comments are open for an year period. Please, write here on Facebook page.