Get PHP content-type from header()

10,266

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");
              }
         }
  }
Share:
10,266

Related videos on Youtube

David Rodrigues
Author by

David Rodrigues

Updated on September 18, 2022

Comments

  • David Rodrigues
    David Rodrigues over 1 year

    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?

  • Orangepill
    Orangepill almost 11 years
    get_headers get's the raw request headers.... I believe the op is after the response headers.