2

I'm trying to send a response to an API for Oauth. Sadly, the Symfony2 docs do a poor job of explaining all the different parts of $response->headers->set(...);.

Here's my response section that's inside of my OauthController:

    $response = new Response();

    $response->setStatusCode(200);
    $response->headers->set('Location', 'url=' . $auth_url);

    return $response->send();

The controller must have a return statement so, does my code look good or how can I replicate header('Location: ' . $auth_url); from normal php?

Thanks!

2
  • Also if you aren't using RedirectResponse and want to set the Location header directly on a Response class, you would do this: $response->headers->set('Location', $auth_url); Jan 25, 2016 at 19:56
  • Perhaps the error in my code was url= in set('Location', 'url=' . $auth_url);. That was in an example I followed.
    – Kenny
    Jan 25, 2016 at 19:59

3 Answers 3

7

Since you want to do a redirect, then you can use RedirectResponse instead of regular Response:

return new RedirectResponse($auth_url);
1
  • Thank you! That did the trick, it's redirecting perfectly now.
    – Kenny
    Jan 25, 2016 at 19:42
0

While @TomaszMadeyski does a good job providing you with a much better alternative, I wanted to take a minute and explain why your code does not work (as it's just fine).

The problem is that a controller much return a response, but it must not send the respond. If you look at the front controller, you'll see that it takes care of sending the response:

$response = $kernel->handle($request);
$response->send();

The reason behind this is that Symfony allows you to edit the response between the controller and the send() (e.g. to add an awesome toolbar or configure the content type).

2
  • Awesome, thanks for this insight! So do you mean a toolbar such as an absolutely positions overlay that's your html, but that exists overtop of another web page? Similar to stumbleupon.com?
    – Kenny
    Jan 25, 2016 at 20:05
  • @Kenny well, you can do everything you want. You can do $response->setContent('Override the cmplete response content!') for instance, or first retrieve the content (getContent()) and then tweak it. Or do something completely different.
    – Wouter J
    Jan 25, 2016 at 20:06
0

If you're doing a redirect, shouldn't your HTTP response code be one of the codes in the 300 range to indicate a redirect?

Also, you might want to checkout this Symfony Cookbook article on redirecting.

1
  • You're probably right. But I scrapped the response->send() and used return new RedirectResponse($auth_url);. Thanks for the information!
    – Kenny
    Jan 26, 2016 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.