StackMaster StackMaster - 1 year ago 55
PHP Question

Can't get setcookie() to work right

I wrote the following class, Cookie.php

class Cookie extends Config{

//Variables declaration
private $cookieName;
private $cookieValue;
private $cookieExpireTime;
private $cookiePath;
private $cookieDomain;
private $cookieSecureThroughSSL;
private $cookieOnlyThroughHTTP;

//Constructor method, creates a new cookie with the assigned values
function __construct($presetCookieName,
$presetCookieDomain = NULL,
$presetCookieSecureThroughSSL = false,
$presetCookieOnlyThroughHTTP = true){

$this->cookieName = $presetCookieName;
$this->cookieValue = $presetCookieValue;
$this->cookieExpireTime = $presetCookieExpireTime;
$this->cookiePath = $presetCookiePath;
$this->cookieDomain = $presetCookieDomain;
$this->cookieSecureThroughSSL = $presetCookieSecureThroughSSL;
$this->cookieOnlyThroughHTTP = $presetCookieOnlyThroughHTTP;

return $this->createCookie();

//Clean cookie from possible malicious HTML code, or mistakenly typed spaces
private function cleanCookieValue($value){
return htmlspecialchars(str_replace(' ', '', $value));

//Create a new cookie function
public function createCookie(){
return setcookie($this->cleanCookieValue($this->cookieName),

And the following test file:

$cookie = new Cookie("testCookie", "Value", 3600, "/");

echo 'Success';
echo 'Failed!';

And I keep getting 'Failed' error (After two or more refreshes as well).
Do you guys see the problem here?

By the way, the following simple example works perfectly:

setcookie("token", "value", time()+60*60*24*100, "/");

echo 'Token succeeded';
echo 'Token failed!';

Answer Source

In the class, you had posted 3rd parameter is $presetCookieExpireTime, not "seconds of life". To make it work - do the

$cookie = new Cookie("testCookie", "Value", time() + 3600, "/");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download