gpt4 book ai didi

php - 从 header() 获取 PHP 内容类型

转载 作者:可可西里 更新时间:2023-10-31 22:12:26 26 4
gpt4 key购买 nike

出于“安全原因”,我需要获取 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

这怎么可能?

最佳答案

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

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

关于php - 从 header() 获取 PHP 内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com