在POST之后在PHP中设置Location标头时,请避免使用HTTP 302响应代码 [英] Avoid HTTP 302 response code when setting the Location header in PHP after POST
问题描述
我需要为POST请求添加 201 Created
响应代码和Location标头,但由于某种原因,我仍然得到302响应。
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.
这就是我所拥有的:
header('HTTP/1.1 201');
header("Location: ..."); // The new resource URL
header('Content-type: application/json; charset=utf-8');
echo $response;
exit;
我试过删除内容类型, echo
和退出
没有任何运气,仍然得到302.我读到我需要指定两个标题,但这就是我正在做的事,没有运气。我也尝试过:
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);
没有,仍然有302:(
Nothing, still got 302 :(
有人知道我没看到什么吗?
Does anybody knows what I am not seeing?
谢谢。
推荐答案
更改订单:
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状态代码。
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;
这篇关于在POST之后在PHP中设置Location标头时,请避免使用HTTP 302响应代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!