Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : Detect Content-Type of the page

Tags:

php

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 .

like image 354
Raptor Avatar asked Jan 14 '23 13:01

Raptor


1 Answers

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'];
like image 144
BlitZ Avatar answered Jan 25 '23 19:01

BlitZ