Avoid HTTP 302 response code when setting the Location header in PHP after POST

烂漫一生 提交于 2019-12-11 03:23:48

问题


I need to put a 201 Created Response code and a Location header for a POST request, but for some reason I am still getting a 302 response.

This is what I have:

header('HTTP/1.1 201');
header("Location: ..."); // The new resource URL
header('Content-type: application/json; charset=utf-8');
echo $response;
exit;

I have tried removing the content type, the echo and the exit without any luck, still getting the 302. I read that I need to specify both headers, but that's what I am doing and no luck. I also tried with:

header("Location: ...", TRUE, 201);

Nothing, still got 302 :(

Does anybody knows what I am not seeing?

Thanks.


回答1:


Change the order around:

header("Location: ..."); // The new resource URL
header('HTTP/1.1 201 Created');
header('Content-type: application/json; charset=utf-8');
echo $response;
exit;

Test:

# curl -i "http://localhost/projects/scratch/302.php"
HTTP/1.1 201 Created
Date: Sun, 29 Jan 2012 23:09:02 GMT
Server: Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By: PHP/5.3.5
Location: ...
Content-Length: 0
Content-Type: application/json; charset=utf-8

Another way

Keep the original order, but force a 201. According to the PHP docs:

it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

header('HTTP/1.1 201 Created', true, 201);
header("Location: ..."); // The new resource URL
header('Content-type: application/json; charset=utf-8');
echo $response;
exit;


来源:https://stackoverflow.com/questions/9057587/avoid-http-302-response-code-when-setting-the-location-header-in-php-after-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!