doutou1922 2015-03-14 23:08
浏览 49
已采纳

在PHP中设置HTTP响应代码(在Apache下)

Given the following two methods for setting a HTTP response code in PHP (specifically, under Apache):

Method 1:

http_response_code(404);

Method 2:

header("HTTP/1.0 404 Not Found");

My questions are:

  1. Aside from the fact that http_response_code is only available in PHP 5.4 or greater, what are the differences between the two approaches and why/when to use one over the other?
  2. Where does the Reason Phrase come from when using the first example? (I've checked and a Reason Phrase is generated from somewhere)
  • 写回答

1条回答 默认 最新

  • dongwen4487 2015-03-15 01:02
    关注

    Since I'm being downvoted into oblivion for no apparent reason, I've managed to answer this myself by scouring through the PHP source code. Hopefully this serves as a reference for anyone else trying to work this out.

    The two methods are essentially functionally equivalent. http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h.

    Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method. Note also that http_response_code is only available in PHP 5.4.0 and higher.

    In summary - The differences between http_response_code and header for setting response codes:

    1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.

    2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header function.

    3. http_response_code is only available in PHP 5.4.0 and higher

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值