mbstring_binary_safe_encoding() WordPress Function

The mbstring_binary_safe_encoding() function is used to ensure that a string is encoded in a way that is safe for binary data. This function is especially important for strings that contain non-ASCII characters, as they can be encoded in a way that is not compatible with binary data.

mbstring_binary_safe_encoding( bool $reset = false ) #

Set the mbstring internal encoding to a binary safe encoding when func_overload is enabled.


Description

When mbstring.func_overload is in use for multi-byte encodings, the results from strlen() and similar functions respect the utf8 characters, causing binary data to return incorrect lengths.

This function overrides the mbstring encoding to a binary-safe encoding, and resets it to the users expected encoding afterwards through the reset_mbstring_encoding function.

It is safe to recursively call this function, however each mbstring_binary_safe_encoding() call must be followed up with an equal number of reset_mbstring_encoding() calls.

Top ↑

See also


Top ↑

Parameters

$reset

(bool)(Optional) Whether to reset the encoding back to a previously-set encoding.

Default value: false


Top ↑

Source

File: wp-includes/functions.php

function mbstring_binary_safe_encoding( $reset = false ) {
	static $encodings  = array();
	static $overloaded = null;

	if ( is_null( $overloaded ) ) {
		if ( function_exists( 'mb_internal_encoding' )
			&& ( (int) ini_get( 'mbstring.func_overload' ) & 2 ) // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated
		) {
			$overloaded = true;
		} else {
			$overloaded = false;
		}
	}

	if ( false === $overloaded ) {
		return;
	}

	if ( ! $reset ) {
		$encoding = mb_internal_encoding();
		array_push( $encodings, $encoding );
		mb_internal_encoding( 'ISO-8859-1' );
	}

	if ( $reset && $encodings ) {
		$encoding = array_pop( $encodings );
		mb_internal_encoding( $encoding );
	}
}


Top ↑

Changelog

Changelog
VersionDescription
3.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More