Using WordPress ‘mbstring_binary_safe_encoding()’ PHP function

The mbstring_binary_safe_encoding() WordPress PHP function sets the mbstring internal encoding to a binary safe encoding when func_overload is enabled.

Usage

mbstring_binary_safe_encoding($reset = false);

Parameters

  • $reset (bool) – Optional. Whether to reset the encoding back to a previously-set encoding. Default: false.

More information

See WordPress Developer Resources: mbstring_binary_safe_encoding()

Examples

Setting binary safe encoding

// Ensure binary-safe encoding is used
mbstring_binary_safe_encoding();
// Perform operations that require binary-safe encoding
// ...
// Reset encoding to the original setting
reset_mbstring_encoding();

Working with binary data

// Set binary safe encoding
mbstring_binary_safe_encoding();

// Load binary data from a file
$binary_data = file_get_contents('example.bin');

// Perform operations on binary data
// ...

// Reset encoding back to the original setting
reset_mbstring_encoding();

Recursive calls

function perform_binary_operations() {
  // Set binary safe encoding
  mbstring_binary_safe_encoding();

  // Perform operations that require binary-safe encoding
  // ...

  // Reset encoding to the original setting
  reset_mbstring_encoding();
}

// Calling the function twice, each call sets and resets the encoding
perform_binary_operations();
perform_binary_operations();

Using with image manipulation

// Set binary safe encoding
mbstring_binary_safe_encoding();

// Load image data
$image_data = file_get_contents('example.jpg');

// Perform image manipulation operations
// ...

// Save manipulated image
file_put_contents('example_modified.jpg', $image_data);

// Reset encoding back to the original setting
reset_mbstring_encoding();

Binary-safe string operations

// Set binary safe encoding
mbstring_binary_safe_encoding();

// Binary data as a string
$binary_string = "example\x00binary\x00data";

// Get the length of the binary string
$length = strlen($binary_string);

// Reset encoding back to the original setting
reset_mbstring_encoding();

// Output: Length of the binary string is 19
echo "Length of the binary string is {$length}";