smiley_kool Posted August 11, 2009 Share Posted August 11, 2009 How can I set a cookie the first time page loads? Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted August 11, 2009 Share Posted August 11, 2009 http://php.net/manual/en/features.cookies.php setcookie Quote Link to comment Share on other sites More sharing options...
smiley_kool Posted August 11, 2009 Author Share Posted August 11, 2009 i have set the cookie.like this $total=100 setcookie("total", $total, time()+(60*60*24)); but my problem is on page load this cookie is not set. until i refresh this page , this cookie wont set Quote Link to comment Share on other sites More sharing options...
priti Posted August 11, 2009 Share Posted August 11, 2009 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 Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted August 11, 2009 Share Posted August 11, 2009 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.