Slim: Can't create 200 OK response with Location header

I’d like to respond 200 OK with Location HTTP header, but what I’m getting is 302 Found instead:

    return $response
            ->withHeader('Location', '/upload/' .basename($filePath))
            ->withStatus(200)
            ;

The same happens when I try to use 204 No Content response.

Surprisingly 201 Created works as expected. Can we make it work for 200 as well for clients that do not know how to handle 201, please?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 16 (16 by maintainers)

Commits related to this issue

Most upvoted comments

FWIW this also works:

<?php header('Location: /foo'); http_response_code(202);

So revising App::respond() to include an explicit http_response_code() call at the end should clean this up, if we don’t want to start handling individual headers differently.

This is a PHP feature. From the header manual page:

The second special case is the “Location:” header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

See #2309 for a PR.

Seems like we could work around that behavior though, based on:

https://github.com/php/php-src/blob/a51cb393b1accc29200e8f57ef867a6a47b2564f/main/SAPI.c#L814-L827

So the PSR-7 message format starts doing what you’d expect it to do.

Basically you’d have to treat the Location header uniquely, passing the response code along with the redirect.

Just checked RFC 7231: https://tools.ietf.org/html/rfc7231, and while it mentions 3xx and 201 explicitly, it also doesn’t say that other status codes can’t be used with the Location header. See: https://tools.ietf.org/html/rfc7231#section-7.1.2. So this is a case of the runtime being overly “helpful”, removing fidelity from the PSR-7 representation.