【问题标题】:Get PHP content-type from header()从 header() 获取 PHP 内容类型
【发布时间】:2013-07-12 20:16:16
【问题描述】:

出于“安全原因”,我需要获取 PHP 的内容类型。例如,如果你使用了函数header("Content-type: text/html; charset=utf-8"),那么在未来的执行时间,我如何可以分别接收到内容类型(text/html)和字符集(utf-8)?

我真正的问题是知道正在使用哪个字符集并在必要时对其进行修改,而无需重新定义信息Content-type。即如果内容类型为application/xml,则保留它,但更改only 字符集。

例如

Original:    Content-type: text/html
First:       -> set to application/xml.
             Content-type: application/xml
Second:      -> set charset.
             Content-type: application/xml; charset=utf-8
Third:       -> set to text/html
             Content-type: text/html; charset=utf-8

这怎么可能?

【问题讨论】:

  • 你要抓Accept 标头

标签: php http header content-type


【解决方案1】:

您可以使用函数headers_list 来获取响应标头。从那里应该只是解析出相关的标题并在需要时重写。

  $headers = headers_list();
  // get the content type header
  foreach($headers as $header){
         if (substr(strtolower($header),0,13) == "content-type:"){
              list($contentType, $charset) = explode(";", trim(substr($header, 14), 2));
              if (strtolower(trim($charset)) != "charset=utf-8"){
                   header("Content-Type: ".trim($contentType)."; charset=utf-8");
              }
         }
  }

【讨论】:

    【解决方案2】:

    你也可以使用函数get_headers()

    http://php.net/manual/en/function.get-headers.php

    请记住,您不能“仅修改”内容类型。如果你想改变它,你必须再次调用 header() 函数。

    【讨论】:

    • get_headers 获取原始请求标头....我相信操作在响应标头之后。
    猜你喜欢
    • 2014-02-10
    • 1970-01-01
    • 2011-05-02
    • 2011-01-05
    • 1970-01-01
    • 2013-07-09
    • 2013-03-22
    • 2016-07-11
    • 2012-09-13
    相关资源
    最近更新 更多