从header()获取PHP内容类型

时间:2013-07-15 03:12:50

标签: php http header content-type

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

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

实施例

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

怎么可能?

2 个答案:

答案 0 :(得分:7)

您可以使用函数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");
              }
         }
  }

答案 1 :(得分:0)

您还可以使用函数get_headers()

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

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