简体   繁体   English

从header()获取PHP内容类型

[英]Get PHP content-type from header()

I need to get the content-type of PHP for "security reasons". 我需要出于“安全原因”获取PHP的内容类型。 For example, if you used the function header("Content-type: text/html; charset=utf-8") , how, at a future time of execution, I can receive the content-type ( text/html ) and charset ( utf-8 ) separately? 例如,如果您使用了函数header("Content-type: text/html; charset=utf-8") ,那么在将来的执行时,我将如何接收内容类型( text/html )和charset ( utf-8 )分开?

My real problem is knowing which charset is being used and modify only it, if necessary, without having to redefine the information Content-type . 我真正的问题是知道正在使用哪个charset并在必要时修改它,而不必重新定义Content-type信息。 Ie if content-type is application/xml , keep it, but change the only charset. 即如果content-type是application/xml ,请保留它,但更改唯一的 charset。

Ex. 防爆。

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

How it is possible? 怎么可能?

You can use the function headers_list to get the response headers. 您可以使用函数headers_list来获取响应标头。 From there is should be just parsing out the relevant header and rewriting if needed. 从那里应该只是解析出相关的标题并在需要时重写。

  $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");
              }
         }
  }

You can also use function get_headers() 你也可以使用函数get_headers()

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

Just keep in mind that you can not "only modify" content-type. 请记住,您不能“仅修改”内容类型。 If you want to change it, you have to call header() function again. 如果要更改它,则必须再次调用header()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM