Jump to content

How can I set a cookie the first time page loads?


smiley_kool

Recommended Posts

then you can set cookies with help of javascript on page event Onload

 

one more thing you can try:

 

place setcookie() function on start of page.  "This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. "

 

Hope it helps

Cookies are only available on the next request. I suppose you can create a wrapper class around it to handle it.

 

<?php
class CookieJar implements ArrayAccess
{
static private $_instance;
private $_cookies = array();

private function __construct()
{
	$this->_cookies = $_COOKIE;
}

static public function getInstance()
{
	if (!self::$_instance) {
		self::$_instance = new self();
	}

	return self::$_instance;
}

public function getCookie($name)
{
	if (!$this->offsetExists($name)) {
		return false;
	}
	else {
		return $this->_cookies[$name];
	}
}

public function setCookie($name, $value, $expire = 0, $path = null, $domain = null, $secure = false, $httponly = false)
{
	setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
	$this->_cookies[$name] = $value;

	return $this;
}

public function offsetExists($offset)
{
	return isset($this->_cookies[$offset]);
}

public function offsetSet($offset, $value)
{
	$this->setCookie($offset, $value);
}

public function offsetUnset($offset)
{
	setcookie($offset, false, time() - 3600);
	unset($this->_cookies[$offset]);
}

public function offsetGet($offset)
{
	return $this->getCookie($offset);
}
}

$cookies = CookieJar::getInstance();

$cookies['foo'] = 'bar'; // set a cookie
unset($cookies['foo']); // remove a cookie

$cookies->setCookie('bar', 'foo', time() + 3600); // set a cookie with custom parameters

echo $cookies['bar']; // get a cookie

 

Note that this is one of the very few cases where the singleton pattern is warranted.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.