José Carlos José Carlos - 8 months ago 89
PHP Question

ZF2 read HTTP Cookie

I have a file (caller.php) which create a cookie in HTTP response and then redirect to a controller in a ZF2 application (LoginController).


setcookie("_ga", "GA1.2.1622977711.1433494392");
setcookie("_gat", "1");

header("Location: http://gnsys.local/publico/login");


use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Http\Response;

class LoginController extends BasePublicController{

public function indexAction(){

$response = $this->getResponse();

foreach ($response->getHeaders() as $header) {
echo "Campo: " . $header->getFieldName() . ' with value ' . $header->getFieldValue() . "<br />";

return new ViewModel();

When LoginController is called, I haven't got any header from the HTTP response :((

What am I doing wrong? Why I can't read any value from my http response headers? How can I read all the headers from HTTP Response?

If I do what I want but just only using PHP, LoginController is changed by a file called login.php whith this code:

foreach (getallheaders() as $name => $value) {
echo "$name: $value</br>";

And this code works fine and give me what I want!!! How can I get the same in Zend Framework 2?

Please, help me!!!

Thanks in advance,

José Carlos

Answer Source

You should extract headers from request, but not response:

foreach ($this->getRequest()->getHeaders() as $header) {
   echo 'Campo: ' . $header->getFieldName() . ' with value ' . $header->getFieldValue() . '<br />';

To get cookies only use next:

foreach ($this->getRequest()->getCookie() as $name => $value) {
    echo 'Campo: ' . $name . ' with value ' . $value . '<br />';

Set cookie from action:

public function callerAction()
    $cookie = new \Zend\Http\Header\SetCookie();

    /** @var \Zend\Http\Response $response */
    $response = $this->getResponse();

    return $this->redirect()->toUrl('/publico/login');