Avoid HTTP 302 response code when setting the Loca

2019-07-16 14:49发布

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条回答
在下西门庆
2楼-- · 2019-07-16 14:56

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;
查看更多
登录 后发表回答