POST后在PHP中设置Location标头时,请避免使用HTTP 302响应代码


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

我需要为POST请求放入201 Created响应代码和Location标头,但由于某种原因,我仍然得到302响应。

这就是我所拥有的:

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

我尝试删除内容类型、echoexit,但没有成功,仍然得到了302。我读到我需要指定两个标题,但这就是我正在做的,没有运气。我也尝试过:

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

什么都没有,仍然得到302:(

有人知道我没有看到什么吗?

谢谢。

更改订单:

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

测试:

# 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

另一种方式

保持原来的顺序,但强制执行201。根据PHP文档:

它还向浏览器返回REDIRECT(302)状态码,除非已经设置了201或3xx状态码。

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;