Symfony 2如何检查cookie已设置

时间:2015-07-02 12:07:32

标签: php symfony cookies

namespace AppBundle\Helper;

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
use AppBundle\Entity\User;
use Doctrine\ORM\EntityManager;


class lastChangeTimeHelper
{
protected $em;
protected $user;

public function __construct(EntityManager $em, SecurityContext $securityContext)
{
    $this->user = $securityContext->getToken()->getUser();
    $this->em = $em;
}

public function lastChangeTime()
{
    $user = $this->user;
    $em = $this->em;

    $response = new Response();

    if (null == $response->headers->getCookies())
    {
        $response->headers->setCookie(new Cookie('lastChangeTime', time(), time() + (3600 * 48)));
    }

    $currentCookieValue = $response->headers->getCookies()['0']->getValue();
    $currentTime = time();
    $maxTime = 60;

    if ($currentTime-$currentCookieValue < $maxTime)
    {
        $currentCookieValue = $currentTime;
        $response->headers->setCookie(new Cookie('lastChangeTime', $currentCookieValue, time() + (3600 * 48)));
    } else {
        $user->setTime(time());
        $em->persist($user);
        $em->flush();
    }
}
}

我不知道如何正确检查名为 lastChangeTime 的Cookie已设置。如果不是,我会创建一个。 $ currentCookieValue $ currentTime 始终具有相同的值。看起来我的脚本每次尝试调用函数 lastChangeTimeHelper :: lastChangeTime()时都会创建一个新的cookie。

2 个答案:

答案 0 :(得分:2)

使用request获取当前Cookie,您可以使用has()操作检查其是否存在,然后使用get()操作获取其值。请参阅以下代码:

$request = Request::createFromGlobals();
$cookies = $request->cookies;

if (!$cookies->has('lastChangeTime'))
{
    $response->headers->setCookie(new Cookie('lastChangeTime', time(), time() + (3600 * 48)));
}
else
{
    $currentCookieValue = $cookies->get('lastChangeTime');
}

答案 1 :(得分:0)

    $request = Request::createFromGlobals();
    $cookies = $request->cookies;

    if (!$cookies->has('lastChangeTime')) {
        $response->headers->setCookie(new Cookie('lastChangeTime', time(), time() + (3600 * 48)));
    } else {
        $currentCookieValue = $cookies->get('lastChangeTime');
    }

    if ($currentTime-$currentCookieValue < $maxTime)

$currentCookieValue中的变量if ($currentTime-$currentCookieValue < $maxTime)未定义。当我var_dump($cookies)时,它会给我一个

object(Symfony\Component\HttpFoundation\ParameterBag)#400 (1) { ["parameters":protected]=> array(1) { ["PHPSESSID"]=> string(26) "vq0mf8ll7hmq1fae6kqjtfg185" } }

但是你可以看到没有lastChangeTime cookie。