Handle Invalid Encoding Errors in PHP mbstring

PHP mbstring functions expect a supported character-set name. If an application passes a misspelled, empty, or unsupported encoding to mb_strlen(), mb_convert_encoding(), or mb_internal_encoding(), PHP throws ValueError. Validate configurable values before processing text.

Last updated: October 21, 2026.

<?php
$encoding = $_ENV['APP_ENCODING'] ?? 'UTF-8';
$supported = array_map('strtoupper', mb_list_encodings());

if (!in_array(strtoupper($encoding), $supported, true)) {
    throw new InvalidArgumentException('Unsupported character encoding');
}

try {
    $length = mb_strlen($value, $encoding);
} catch (ValueError $error) {
    error_log($error->getMessage());
    throw new RuntimeException('Text configuration is invalid', 0, $error);
}

Keep the original encoding value out of a public error response if it comes from user-controlled input. Log enough context for diagnosis, then return a stable application-level error.

Distinguish an encoding name from invalid text

An unsupported encoding argument and malformed bytes are different problems. The PHP manual states that mb_strlen() throws ValueError for an invalid encoding name. Use mb_list_encodings() when an encoding can come from configuration, a database row, or an integration setting.

If the encoding name is valid but the text may contain malformed bytes, check the data with mb_check_encoding($value, $encoding). That function validates the byte stream; it does not repair it. For imported data, choose explicitly whether to reject the record, request a corrected source file, or scrub malformed sequences. Do not silently guess an encoding for security-sensitive identifiers.

Keep one encoding policy for the application

Prefer a small allowlist such as UTF-8 when the application controls its inputs. Normalize aliases only when a documented integration requires them, and test every accepted value. The official mb_convert_encoding() documentation also treats invalid source and destination encoding names as exceptions.

Catch ValueError at the boundary where configuration or external metadata enters the application. A broad catch (Exception) does not catch PHP errors such as ValueError; catch that class directly or catch Throwable only at a deliberate top-level error boundary.

Continue with fixing invalid UTF-8 in JSON, converting Windows-1252 to UTF-8, and handling PHP ValueError failures.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov