PHP – Check if strings are valid for the specified encoding using mb_check_encoding()

In PHP, the mb_check_encoding() function is used to check if the given strings are valid for the specified encoding. This function validates whether the specified byte stream conforms to the stated encoding rules.

Syntax

bool mb_check_encoding(string $value = null, string $encoding = null)

Parameters

mb_check_encoding() accepts two parameters:

  • $value − The byte stream, string, or array to check. If omitted, it checks all input from the beginning of the request.

  • $encoding − The expected encoding. If omitted, it uses the internal encoding.

Return Value

mb_check_encoding() returns true if the value is valid for the specified encoding, or false on failure.

Example 1: Basic String Validation

<?php
    // Check if string is valid ASCII
    $string = "Hello World";
    $isValid = mb_check_encoding($string, "ASCII");
    
    echo "String: '$string'<br>";
    echo "Valid ASCII: " . ($isValid ? "Yes" : "No") . "<br>";
    
    // Check UTF-8 string
    $utf8String = "Hello ??";
    $isValidUTF8 = mb_check_encoding($utf8String, "UTF-8");
    
    echo "\nString: '$utf8String'<br>";
    echo "Valid UTF-8: " . ($isValidUTF8 ? "Yes" : "No") . "<br>";
?>
String: 'Hello World'
Valid ASCII: Yes

String: 'Hello ??'
Valid UTF-8: Yes

Example 2: Array Validation

<?php
    // Check array values (PHP 7.2+)
    $data = ["Hello", "World", "PHP"];
    $isValidArray = mb_check_encoding($data, "ASCII");
    
    echo "Array validation result: " . ($isValidArray ? "Valid" : "Invalid") . "<br>";
    
    // Mixed array with invalid encoding
    $mixedData = ["Hello", "\xFF\xFE", "World"];
    $isValidMixed = mb_check_encoding($mixedData, "UTF-8");
    
    echo "Mixed array validation: " . ($isValidMixed ? "Valid" : "Invalid") . "<br>";
?>
Array validation result: Valid
Mixed array validation: Invalid

Key Points

  • From PHP 7.2+, the function accepts arrays and validates all keys and values recursively

  • From PHP 8.0+, both parameters can be null

  • Helps prevent invalid encoding attacks by validating input data

  • When $value is omitted, it checks all request input

Conclusion

The mb_check_encoding() function is essential for validating string and array data against specific encodings. It helps ensure data integrity and prevents encoding-related security vulnerabilities in PHP applications.

Updated on: 2026-03-15T09:57:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements