【问题标题】:Can't get setcookie() to work right无法让 setcookie() 正常工作
【发布时间】:2016-09-26 07:58:31
【问题描述】:

我写了下面的类,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,
                     $presetCookieValue,
                     $presetCookieExpireTime,
                     $presetCookiePath='/',
                     $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),
                     $this->cleanCookieValue($this->cookieValue),
                     $this->cleanCookieValue($this->cookieExpireTime),
                     $this->cleanCookieValue($this->cookiePath),
                     $this->cleanCookieValue($this->cookieDomain),
                     $this->cleanCookieValue($this->cookieSecureThroughSSL),
                     $this->cleanCookieValue($this->cookieOnlyThroughHTTP));
}

还有如下测试文件:

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

if(isset($_COOKIE['testCookie'])){
    echo 'Success';
}
else{
    echo 'Failed!';
}

而且我不断收到“失败”错误(在两次或多次刷新之后)。 你们看到这里的问题了吗?

顺便说一下,下面这个简单的例子效果很好:

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

if(isset($_COOKIE['token'])){
    echo 'Token succeeded';
}
else{
    echo 'Token failed!';
}

【问题讨论】:

    标签: php cookies setcookie


    【解决方案1】:

    在课堂上,您发布的第三个参数是$presetCookieExpireTime,而不是“生命秒数”。为了使它工作 - 做

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

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 2017-11-06
      • 2011-09-06
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多