Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PHP content-type from header()

I need to get the content-type of PHP for "security reasons". 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?

My real problem is knowing which charset is being used and modify only it, if necessary, without having to redefine the information Content-type. Ie if content-type is application/xml, keep it, but change the only 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?

like image 619
David Rodrigues Avatar asked Mar 23 '23 04:03

David Rodrigues


1 Answers

You can use the function headers_list to get the response headers. 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");
              }
         }
  }
like image 87
Orangepill Avatar answered Apr 01 '23 06:04

Orangepill