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
- Send correct status code regardless of location header PHP thinks it's clever, but it isn't. Fixes #1730. — committed to kelunik/Slim by kelunik 7 years ago
- Send correct status code regardless of location header PHP thinks it's clever, but it isn't. Fixes #1730. — committed to kelunik/Slim by kelunik 7 years ago
- Send correct status code regardless of location header PHP thinks it's clever, but it isn't. Fixes #1730. — committed to slimphp/Slim by kelunik 7 years ago
- Merge pull request #3139 from adoy/fix-1739 Fixed #1730 (reintroduced in 4.x) — committed to slimphp/Slim by l0gicgate 2 years ago
- send headers in reverse order to prevent a problem documented in Slim https://github.com/slimphp/Slim/issues/1730 — committed to 1ma/jelly by 1ma 2 years ago
FWIW this also works:
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:
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.