Get PHP content type from header ()

I need to get the PHP content type for "security reasons." For example, if you used the header("Content-type: text/html; charset=utf-8") function header("Content-type: text/html; charset=utf-8") , how can I get the content type ( text/html ) and charset ( utf-8 ) separately in the future runtime?

My real problem is to know which encoding is used and only modify it if necessary, without having to redefine the Content-type . Those. if the content type is application/xml , save it, but only change the encoding.

Ref.

 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 is this possible?

+4
source share
2 answers

You can use the headers_list function to get response headers. From there, there should only be a parsing of the corresponding heading and rewriting, if necessary.

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

You can also use the get_headers () function

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

Just keep in mind that you cannot โ€œjust modifyโ€ the type of content. If you want to change it, you need to call the header () function again.

0
source

Source: https://habr.com/ru/post/1491358/


All Articles