In PHP, we can set the Content-Type by :
header('Content-Type: text/plain');
But if I work on a PHP class that requires to show an error message, which the format of the error message is shown according to the content type, e.g. if the page is text/html, it shows HTML-formatted error message; else, show plain text error message.
Is there any function / snippet that I can use to detect the page Content-Type ?
Note: Given that the PHP class file is "attached" to the page by require_once()
UPDATE: From @Tamil's answer, I performed a short test:
<?php
header('Content-Type: text/plain');
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
echo finfo_file($finfo, __FILE__) . "\n";
finfo_close($finfo);
?>
It returns text/x-php only. But I expect the result will return text/plain .
Try headers_list() function:
<?php
header('Content-Type: text/plain');
$headers = headers_list();
var_dump($headers);
?>
Shows (in my case):
array(2) {
  [0]=>
  string(23) "X-Powered-By: PHP/5.4.5"
  [1]=>
  string(24) "Content-Type: text/plain"
}
To normalize result array you may use this:
<?php
header('Content-Type: text/plain');
$headers = headers_list();
foreach($headers as $index => $value) {
    list($key, $value) = explode(': ', $value);
    unset($headers[$index]);
    $headers[$key] = $value;
}
var_dump($headers);
?>
Shows:
array(2) {
  ["X-Powered-By"]=>
  string(9) "PHP/5.4.5"
  ["Content-Type"]=>
  string(10) "text/plain"
}
So, the Content-Type header with normalized array might be obtained like this:
echo $headers['Content-Type'];
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With