How to Set PHP Character Encoding to UTF-8

A flat vector illustration of a violet-blue code document icon featuring a globe symbol and a setting gear. Text: SET PHP UTF-8.

Open an old script or migrate a site and you have seen it: apostrophes render as ’, café shows up as café, emoji become black diamonds. This DevAnswers guide fixes character encoding at every layer PHP touches, from the HTTP header and php.ini to the database and multibyte strings, so output stays UTF-8.

Send the UTF-8 Content-Type Header 

The most direct way to tell a browser how to read your output is the Content-Type response header. It arrives ahead of the body, so the browser knows the encoding before it parses a single tag, and it overrides any charset declared inside the HTML itself. That makes it the most authoritative signal you can send. Set it from PHP with the header() function:

index.php
header('Content-Type: text/html; charset=UTF-8');

// DevAnswers.net
echo "Visitors from Köln to 東京 see this correctly.";

One catch: header() has to run before any output. A stray space before <?php, a blank line in an included file, or an early echo sends the body first, and PHP then warns that headers were already sent. If you hit that, turn on error display to see exactly which file and line printed too early, or wrap your output in ob_start() so nothing is sent until you are ready.

Set default_charset in php.ini 

Calling header() in every script gets old fast. Set the encoding once at the server level with the default_charset directive. Since PHP 5.6 it defaults to UTF-8 and supplies the default encoding for htmlspecialchars(), htmlentities(), and html_entity_decode(), as well as the mbstring and iconv functions when their own encoding settings are left unset. PHP also applies it to the default Content-Type header it sends, so a single value covers most scripts.

php.ini
; DevAnswers.net
default_charset = "UTF-8"

Not sure where your php.ini lives, or which file the web server actually loads? Our guide to finding and editing php.ini walks through it. After the edit, reload PHP-FPM or Apache so the change takes effect, then confirm the active value. This one-liner works on any OS:

Terminal
php -r "echo ini_get('default_charset'), PHP_EOL;"
Output
UTF-8

That reports the setting for the command-line PHP (CLI). Your web server runs a separate SAPI, usually PHP-FPM, which can load a different php.ini. To confirm what visitors actually get, drop a <?php phpinfo(); ?> file in your web root, open it in a browser, and read the default_charset row.

Delete the phpinfo() file the moment you have read the value. Left in your web root it exposes your full PHP configuration, including file paths, versions, and loaded extensions, to anyone who finds the URL.

Declare the Charset in Your HTML 

Headers win when they are present, but they are not always present. If a reader saves your page to disk and reopens it, there is no server to send a header. The HTML5 <meta charset> tag is the fallback: it declares the document’s character encoding directly in the markup. Put it near the top of <head> so the parser reads it before any visible text.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DevAnswers UTF-8 Page</title>
</head>
<body>
    <!-- Your content -->
</body>
</html>

Keep it among the first elements in <head>, before the <title> or any other content. The browser only sniffs the opening bytes of the document for an encoding declaration, so a <meta charset> buried lower down can be missed and the page falls back to a default encoding.

Use utf8mb4 for MySQL and MariaDB 

A classic failure: PHP is clean UTF-8, but text still arrives mangled because the database connection negotiated latin1. Two things fix it, the character set you choose and where you set it on the connection.

First, use utf8mb4, not utf8. In MySQL, utf8 is a deprecated alias for utf8mb3, which stores at most three bytes per character and cannot hold supplementary characters such as emoji. utf8mb4 uses up to four bytes and covers the full Unicode range. Set it directly on the PDO connection through the DSN:

PHP
$dsn = "mysql:host=127.0.0.1;dbname=devans_db;charset=utf8mb4";
$pdo = new PDO($dsn, "devans", $password);

For the full connection pattern with error handling and prepared statements, see our PDO CRUD guide. If you use the mysqli extension instead, call set_charset() on the connection rather than running a SET NAMES query, which the manual specifically advises against:

PHP
$mysqli = new mysqli("127.0.0.1", "devans", $password, "devans_db");
$mysqli->set_charset("utf8mb4");

Whichever extension you use, verify the connection actually negotiated utf8mb4 rather than assuming it. With mysqli, ask the connection directly:

PHP
echo $mysqli->character_set_name();
Output
utf8mb4

Our mysqli CRUD guide covers the rest of the workflow, from prepared statements to fetching results.

Handle Multibyte Strings with mbstring 

UTF-8 breaks the assumption that one byte equals one character. strlen() and substr() work on bytes, so on multibyte text they miscount and can slice through the middle of a character, leaving a corrupted string. The mbstring extension provides character-aware versions that count and cut by character instead:

PHP
mb_internal_encoding("UTF-8");

$city = "Köln";        // the ö is two bytes in UTF-8
echo strlen($city);      // 5 (bytes)
echo mb_strlen($city);   // 4 (characters)
echo mb_substr($city, 0, 2); // "Kö"

Set mb_internal_encoding('UTF-8') near the top of your application. The mb_* functions inherit default_charset, but setting it here makes the encoding explicit per script, so the code stays correct even on a server where the ini value differs. One gotcha: mbstring is not built into PHP by default. On Debian or Ubuntu, install it with sudo apt install php-mbstring and reload PHP-FPM before the functions become available.

Convert Existing Strings to UTF-8 

Importing legacy data or reading a file in another encoding calls for actual conversion, not just a relabel. Older code reached for utf8_encode() and utf8_decode(), but both were deprecated in PHP 8.2 and emit a deprecation notice on PHP 8.2 and later. The replacement is mb_convert_encoding(), which handles ISO-8859-1 and many other encodings:

PHP
// Deprecated since PHP 8.2:
// $utf8 = utf8_encode($latin1);

// Current replacement:
$utf8 = mb_convert_encoding($latin1, "UTF-8", "ISO-8859-1");

The third argument is the source encoding, so name it whenever you know it. It is tempting to let mb_detect_encoding() guess instead, but the manual is clear that detection is not guaranteed, and a wrong guess produces the same mojibake you set out to fix. Detect only as a last resort, and sanity-check the result before you store it.

Run the conversion exactly once. The most common self-inflicted wound here is converting a string that is already UTF-8: feeding clean UTF-8 through an ISO-8859-1-to-UTF-8 conversion double-encodes it, and your accented characters turn into the very garbage you were trying to repair. Convert only at the boundary where data enters your application, then treat everything inside as UTF-8.

Summary 

UTF-8 only holds when every layer agrees. Send the Content-Type header (or set default_charset once), declare <meta charset> in your HTML, connect to the database with utf8mb4, and reach for mb_* functions on any text you measure or slice. Miss one layer and the broken characters reappear; line them all up and the encoding problem stays solved.

Support DevAnswers
Written, tested and maintained by one developer. Your support keeps these guides accurate and ad-light.
Buy me a coffee

Comments

Leave a reply