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

时间:2012-01-29 23:03:29

标签: php http post http-headers httpresponse

我需要为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 :(

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

感谢。

1 个答案:

答案 0 :(得分:11)

更改订单:

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. According to the PHP docs

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

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;
相关问题