2013-07-23 17 views
7

Ho trovato questo argomento Zend Framework 2 - Cookie Concept mentre cercavo informazioni sull'impostazione dei cookie in ZF2, ma sembra che le informazioni incluse in tale argomento non siano aggiornate. codice seguente
ho provato:Zf2 - Come impostare cookie

public function indexAction() 
{ 
    $request = $this->getRequest()->getHeaders()->get('Set-Cookie')->foo = 'bar; 
    $response = $this->getResponse()->getCookie()->baz = 'test'; 
    var_dump($_COOKIE); 
    ... 
    return new ViewModel(); 
} 

Entrambe le linee di uscita di avvertimento:

Warning: Creating default object from empty value 

ho provato anche:

public function indexAction() 
{ 
    $cookie = new SetCookie('test', 'value', 60*60*24); // Zend\Http\Header\SetCookie instance 
    $header = new Cookie(); // Zend\Http\Cookies instance 
    $header->addCookie($cookie); 
    ... 
    return new ViewModel(); 
} 

Esso non restituisce alcun errore o avviso, tutto sembra per essere ok, ma quando provo var_dump ($ _ COOKIE) mostra ancora null.
Sì, il mio browser ha attivato il cookie.

risposta

16

Ecco la mia soluzione che sto attualmente utilizzando.

$cookie = new SetCookie('key', 'value', time() + 365 * 60 * 60 * 24); // now + 1 year 
$headers = $this->getResponse()->getHeaders(); 
$headers->addHeader($cookie); 
+0

Grazie, funziona! – user1409508

+0

come possiamo sovrascrivere su questo cookie e come possiamo rimuoverlo ho cercato ma non ho trovato nulla di utile –

Problemi correlati