How to Set HTTP Header to UTF-8 in PHP

While working with PHP, sometimes it is necessary to set Header to UTF-8. In this tutorial, we will illustrate to you how to do that with the help of the header() function. The latter is used for sending a raw HTTP header.

So, let’s see how to set Header to UTF-8 using header().

Watch a course Learn object oriented PHP

Using header()

Below, you can see how to use the header() function for setting Header to UTF-8.

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

So, anytime before sending any output to the client, you need to run the code above.

All you need is adding it to the beginning of the page. Be careful not to leave any blank space before it, as it will lead to an error. For checking whether the headers are already sent or not, just apply the headers_sent function.

Describing the header() Function

This function operates on all PHP versions.

It is used for sending a raw PHP header.

An essential thing to note: the header() function must be called before sending any actual output.

For more examples of using the header() function, you can refer to this source.

Describing the headers_sent Function

This PHP function allows checking whether or where the headers were sent. But note that after the header block has already been sent, no more header lines can be added with the header function.

For more examples of using the header_sent() function, you can refer to this source.