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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.