Image

Knowledge base → Forced encoding specification in PHP when connecting to a MariaDB database

[Scripts]
Date of publication: 26.12.2024

By default, the utf8mb4 encoding is used for database connections on all hosting plans. In rare cases, when a website was developed a long time ago, the encoding may display incorrectly.

Instead of normal letters, you will see so-called "mojibake," symbols that resemble machine hieroglyphs. This happens because the database and all its tables are in a different encoding than utf8mb4. Meanwhile, all old websites were developed using the Windows-1251 encoding.

To fix the incorrect display, you need to forcefully specify the encoding for the database connection in your CMS.

You need to open the PHP configuration file and after the lines specifying the database connection name, login, and password, add the following line:

ini_set('default_charset', 'Windows-1251');

This configuration forcefully specifies the connection encoding.

The final version of the settings file should look something like this:

...
$hostname_dbconn = "localhost";
$database_dbconn = "DATABASE-NAME";
$username_dbconn = "DATABASE-USER";
$password_dbconn = "PASSWORD";

ini_set('default_charset', 'Windows-1251');
...

Now, refresh the page using the key combination Ctrl + F5 (clearing the browser cache) - the site's encoding display should now work correctly.

To ensure which encoding the site is using, you can press the key combination Ctrl + u in the browser. In the opened tab, at the beginning of the HTML code, find a line like:

<meta http-equiv="content-type" content="text/html; charset=windows-1251" />




No Comments Yet