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 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止