We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Setting headers when redirecting doesn't work - headers don't get set

In the example below I'm calling "first" and then redirecting to "second". I would expect the header "User-Agent" to show the value "Internal" inside the "second" action but there are no response headers, and the request headers are unchanged.

What am I doing wrong, and how can I create an interaction between two actions where headers are exchanged?

The "fakeController" class:


class FakeController extends Controller
{
    public function firstAction()
    {
        $this->response->setHeader("User-Agent","Internal");

        $this->response->redirect("fake/second");
    }

    public function secondAction()
    {
        $rsHdr = $this->response->getHeaders();
        $rqHdr = $this->request->getHeaders();

    }
}

All its working just fine. Headers are added properly. U didnt test it right.

  1. open chrome (for example)
  2. start console (f12)
  3. open network tab in console, clear all
  4. now open fake/first
  5. you will see 2 request in network : first and second- click on first and see responce header- all is set and u have Internal user agent.

What u try to achieve?

I'm trying to simulate some interaction between two servers (first and second) - specifically I want to test headers sent and received.

In the example shown, I would like the header "User-Agen" to have the value "Internal" when I retrieve it in secondAction. But what I do in firstAction has no effect on the headers in secondAction.

Well... simulation between two servers- i think u must consider the communication using... some web services, AJAX, REST, SOAP, etc.

but if we back to your example- u can get headers with curl - but still - depends of communication logick.



9.5k
Accepted
answer

Thanks, I found a way to get what I want.

I still don't understand how redirect works. After a redirect the headers are still the original ones, can't change or add headers. Even if I redirect to another virtual host on the same server.

So with curl it can be done. I now make a curl call from the "first" controller to the "second" controller and back again. I use headers to guard against recursion. I've set it up so "first" and "second" are on different virtual hosts to get more separation, though (not tested) I guess it would be the same on a single host.