doudao1282 2015-05-23 08:17
浏览 161
已采纳

响应头重复(流明)

Continuation of: Setting response headers with middleware in Lumen

When using the following exception handler in Lumen, the X-Powered-By header is duplicated, even though $replace (the third parameter of the header() method) defaults to true (even setting it manually, as below, does not work).

public function render($request, Exception $e)
{
    if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
    {
        return response(view('not-found'), 404)->header('X-Powered-By', env('APP_NAME')."/".env('APP_VER'), true);
    }

    return parent::render($e);
}

The response header:

HTTP/1.0 404 Not Found
Date: Sat, 23 May 2015 08:05:13 GMT
Server: Apache
X-Powered-By: PHP/5.6.3
Cache-Control: no-cache
X-Powered-By: AppName/1.0.0
Connection: close
Content-Type: text/html; charset=UTF-8

The only thing that works is to use header_remove('X-Powered-By') just before the call to ->header. I should not have to do this, due to the $replace parameter being set accordingly.

Are there any better ways to prevent the duplication of the X-Powered-By header?

  • 写回答

2条回答 默认 最新

  • dourong8495 2015-05-27 20:44
    关注

    I couldn't get this to work with method chaining, however, if I did this:

    header('X-Powered-By: '.env('APP_NAME')."/".env('APP_VER'));
    return response(view('not-found'), 404);
    

    ... it worked as you desire. But please do notice there is only one argument in the header per the PHP manual:

    void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
    

    The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type.

    Source: http://php.net/manual/en/function.header.php

    ... meaning, it's not a "replace this with that" type of item like str_replace. If the string you type into the first argument is similar to another header item, it will replace it with whatever you've typed automatically.

    Side note: I also tried setting the third argument of the response function to an array including the X-Powered-By header to no avail.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了