W3docs

How to Set HTTP Header to UTF-8 in PHP

If you want to learn how to set the HTTP header to UTF-8 in PHP, then read this snippet, examine and run the examples, that are demonstrated in it.

While working with PHP, you may need to set the HTTP header to UTF-8. This tutorial shows how to do it using the <kbd class="highlighted">header()</kbd> function, which sends a raw HTTP header.

Using header()

The following code sets the Content-Type header to UTF-8:

php header() function to set Header to UTF-8

header('Content-Type: text/html; charset=utf-8');

Place this code at the very beginning of your script, before any output is sent to the client. Ensure there are no blank lines or whitespace before the opening <?php tag, as this will trigger a "headers already sent" error. To check if headers have already been sent, use the <kbd class="highlighted">headers_sent()</kbd> function:

if (!headers_sent()) {
    header('Content-Type: text/html; charset=utf-8');
}

Describing the header() Function

The <kbd class="highlighted">header()</kbd> function is available in all PHP versions and is used to send a raw HTTP header. It must be called before any actual output is sent to the browser.

For more examples, refer to the official PHP documentation.

Describing the headers_sent Function

The <kbd class="highlighted">headers_sent()</kbd> function checks whether or where the HTTP headers have already been sent. Once the header block is sent, no additional headers can be added using header().

For more examples, refer to the official PHP documentation.