Set/Get Cookie using PHP and JavaScript

May 15th, 2007

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

$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>

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

$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.

 

 

Possibly Related posts:

  1. lahlah
    May 22nd, 2008 at 09:47 | #1

    Is it possible to save and get cookies via javascript inside a Blogger blog?

  2. Satya Prakash Karan
    May 22nd, 2008 at 10:55 | #2

    If it is possible to add your javascript code and javascript file then it should be possible doing that also.
    I never tried that.

  3. lahlah
    May 22nd, 2008 at 11:05 | #3

    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.

  4. Satya Prakash Karan
    May 22nd, 2008 at 22:02 | #4

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

  5. Deaddancer
    October 3rd, 2008 at 11:57 | #5

    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)

  6. Satya Prakash Karan
    October 3rd, 2008 at 12:10 | #6

    yes, cookie will be accessed lately. it will be late by one step!

Comments are closed.