David Rodrigues
David Rodrigues

Reputation: 12532

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?

Upvotes: 4

Views: 10668

Answers (2)

Orangepill
Orangepill

Reputation: 24645

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

Upvotes: 7

edo.schatz
edo.schatz

Reputation: 99

You can also use function get_headers()

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.

Upvotes: 0

Related Questions