Search code examples
phpzend-frameworkcookieshttp-headershttpresponse

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).

caller.php

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

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

LoginController

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?


Solution

  • 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();
        $cookie->setName('foo')
            ->setValue('bar')
            ->setDomain('gnsys.local')
            ->setPath('/')
            ->setHttponly(true);
    
        /** @var \Zend\Http\Response $response */
        $response = $this->getResponse();
        $response->getHeaders()->addHeader($cookie);
    
        return $this->redirect()->toUrl('/publico/login');
    }