wppaste
WordPress

ParagonIE_Sodium_Compat::memzero( string|null $var ): void

Source
wp-includes/sodium_compat/src/Compat.php:3837

Wipes a string variable passed by reference using the native sodium_memzero() function when the sodium extension is present, otherwise falls back to the old \Sodium\memzero() polyfill. If neither is available it throws a SodiumException instead of silently doing nothing, since sodium_compat cannot securely erase memory in pure PHP. Use it right before a sensitive string (a key, nonce, or decrypted payload) goes out of scope, and pair it with unset() as extra insurance.

It's actually not possible to zero memory buffers in PHP. You need the native library for that.

Compatibility

WordPress
core
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$varstring|null

Return value

void

Code examples

Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.

Zero out a sensitive string after using it

Pull a value out of post meta to stand in for a sensitive string, then try to wipe it once it has been used.

$secret = (string) get_post_meta( 2, 'price', true );

printf( 'Before: %s' . PHP_EOL, esc_html( $secret ) );

try {
	ParagonIE_Sodium_Compat::memzero( $secret );
	printf( 'After: %s' . PHP_EOL, esc_html( var_export( $secret, true ) ) );
} catch ( SodiumException $e ) {
	printf( 'memzero() refused: %s' . PHP_EOL, esc_html( $e->getMessage() ) );
}

The visible result depends on whether the server's PHP build has the sodium extension enabled; on builds without it and without the legacy Sodium extension the call throws.

Guard a call to memzero() so it never throws

Check which code path memzero() will take before handing it an API key you want cleared from memory.

$api_key = 'sk_test_51H0000000000000';

if ( ParagonIE_Sodium_Compat::useNewSodiumAPI() ) {
	ParagonIE_Sodium_Compat::memzero( $api_key );
	printf( 'Wiped via the native sodium extension. Value now: %s' . PHP_EOL, esc_html( var_export( $api_key, true ) ) );
} elseif ( ParagonIE_Sodium_Compat::use_fallback( 'memzero' ) ) {
	ParagonIE_Sodium_Compat::memzero( $api_key );
	printf( 'Wiped via the legacy Sodium extension.' . PHP_EOL );
} else {
	unset( $api_key );
	printf( 'No native wiping available, unset() the variable instead.' . PHP_EOL );
}

Common problems and fixes · 4

Why does memzero() throw a SodiumException instead of just clearing the string?

The source only clears memory when either the native sodium extension (useNewSodiumAPI()) or the legacy Sodium extension (use_fallback('memzero')) is present. When neither exists it throws, because pure PHP userland code has no way to overwrite a string's memory buffer. - Wrap the call in try/catch and fall back to unset($var). - Check ParagonIE_Sodium_Compat::useNewSodiumAPI() or use_fallback('memzero') before calling.

Why does my variable still show its old value after calling memzero()?

Even on success, memzero() only overwrites the memory sodium controls, it can't stop PHP's own copy-on-write engine from having made other copies of the string elsewhere in the process. Treat it as best-effort hardening, not a guarantee. - Still call unset($var) afterward. - Avoid keeping additional copies of the sensitive value in other variables.

Why do I get a 'only variables should be passed by reference' error?

The method signature takes &$var by reference, so PHP requires an actual variable, not a literal, a function return value, or an array element accessed by expression.

Is calling memzero() the same as calling sodium_memzero() directly?

No. sodium_memzero() is the raw native PHP function this method delegates to when available. ParagonIE_Sodium_Compat::memzero() adds a scalar type check, a legacy-extension fallback, and an explicit exception when no native wiping is possible at all.

Alternatives and related functions

sodium_memzero
When you already know the sodium PHP extension is loaded and don't need the compat layer's fallback or exception handling.
ParagonIE_Sodium_Compat::useNewSodiumAPI
When you want to detect ahead of time whether memzero() will use the native extension instead of catching an exception after the fact.
ParagonIE_Sodium_Compat::use_fallback
When you need to know whether the legacy \Sodium\ extension fallback path is available before calling memzero().
SodiumException
When you need to catch or inspect the specific exception memzero() throws instead of a generic Exception.

Performance profile

How much work a call to ParagonIE_Sodium_Compat::memzero() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Trivial

Touches nothing outside its own arguments.

Scaling
Constant

No loop in the body: the same number of instructions runs whatever you pass in.

Instructions
13–22

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 27.

Plugin surface
None

Nothing here hands control to plugin code.

Called by
39

39 places in core call this, so the cost is paid more often than your own code shows.

What one call costs · 3 distinct outcomes

One number would be a lie: the work depends on which branch runs. These are every distinct cost ParagonIE_Sodium_Compat::memzero() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
::useNewSodiumAPI()13::ParagonIE_Sodium_Core_Util(), ::useNewSodiumAPI(), sodium_memzero()
!::useNewSodiumAPI() && !::use_fallback()17::ParagonIE_Sodium_Core_Util(), ::useNewSodiumAPI(), ::use_fallback()
!::useNewSodiumAPI() && ::use_fallback()19–22::ParagonIE_Sodium_Core_Util(), ::useNewSodiumAPI(), ::use_fallback(), Sodium\\memzero()

Across PHP versions

Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 27 instructions, 13–22 executed per call, 3 branches. The work does not change between versions.

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Uses · 5

Used by · 39

Show all 39

Source code

    public static function memzero(        #[\SensitiveParameter]        &$var    ) {        /* Type checks: */        ParagonIE_Sodium_Core_Util::declareScalarType($var, 'string', 1);         if (self::useNewSodiumAPI()) {            /** @psalm-suppress MixedArgument */            sodium_memzero($var);            return;        }        if (self::use_fallback('memzero')) {            $func = '\\Sodium\\memzero';            $func($var);            if ($var === null) {                return;            }        }        // This is the best we can do.        throw new SodiumException(            'This is not implemented in sodium_compat, as it is not possible to securely wipe memory from PHP. ' .            'To fix this error, make sure libsodium is installed and the PHP extension is enabled.'        );    }

Changelog

Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

About this page

Parsed data
Generated from the wordpress-develop 7.1.0 tag, from src/wp-includes/sodium_compat/src/Compat.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.