Magnar Myrtveit
Magnar Myrtveit

Reputation: 2740

Set content type without charset

I'm trying to set the header Content-Type to text/html, but without specifying the charset. If I run the following code:

header('Content-Type: text/html');
var_dump(headers_list());

I get the following output:

['Content-type: text/html;charset=UTF-8']

The charset parameter is added automatically! And Content-Type is changed to Content-type. The same happens with any content type with the type text. For example Content-Type: text/foobar becomes Content-type: text/foobar;charset=UTF-8.

If I specify any additional parameters, they are kept. For example Content-Type: text/foobar; param=value becomes Content-type: text/foobar; param=value;charset=UTF-8.

If I specify the charset parameter, the header is not changed. For example Content-Type: text/html; charset=ISO-8859-1 stays Content-Type: text/html; charset=ISO-8859-1. In this case, the header field name is not changed from Content-Type to Content-type either.

If I specify a content type that has a type other than text, the header is not changed. For example Content-Type: foo/bar stays the same.

Is it not possible to specify a text-based content type without the charset parameter? I'm using PHP 7.1.1 and Apache 2.4.26.

Upvotes: 4

Views: 1852

Answers (1)

Jake
Jake

Reputation: 1067

You have encountered what I believe to be a bug in PHP:

https://bugs.php.net/bug.php?id=75922

I have confirmed that the following can be used as a workaround:

$defaultCharset = \ini_get('default_charset');
\ini_set('default_charset', '');
\header('Content-Type: text/html');
\ini_set('default_charset', $defaultCharset);

Setting the default_charset to an empty string before calling header() prevents PHP appending the charset parameter (tested with PHP 7.3). However, as "Setting default_charset to an empty value is not recommended", the code above immediately restores the previous value (it does not appear to matter that the headers are not actually sent until the first part of the content is).

In my case, there are some hardcoded HTML files to serve with a different charset to the default, declared in a <meta> element.

(I also found that \header('Content-Type: text/html; charset=') seems to work in Firefox and Chrome, but does result in an empty charset parameter in the HTTP header, which may cause issues with some browser versions.)

Upvotes: 1

Related Questions