WordPress at a glance

is_serialized() WP 2.0.5

Check the given value if it's a serialized string.

If the given value is not a string, false will be returned because serialized data is always a string.

But you should keep in mind that the function doesn't validate the serialized string, so if it's corrupted, it still will be determined as a serialized string.

Is the basis for: maybe_serialize()
✈ 1 time = 0.000011s = very fast | 50000 times = 0.04s = speed of light | PHP 7.0.8, WP 4.6.1

No Hooks.

Return

true/false. False if not serialized and true if it was.

Usage

is_serialized( $data, $strict );
$data(string) (required)
The value to check to see if it's serialized.
$strict(true/false)
Whether to be strict about the end of the string. When this parameter is true it's supposed that the string should end either with ; or } character.
Default: true

Examples

#1 Check if the string is a serialized string

Suppose we have a serialized string from such array array( 'foo'=>'bar' );:

is_serialized( 'a:1:{s:3:"foo";s:3:"bar";}' ); //> true

// Doesn't validate the end
is_serialized( 'a:1:{s:3:"foo";s:3:"bar";' ); //> true

// Non-serialized data
is_serialized( 'hello world' ); //> false

is_serialized( array('foo') ); //> false

Changelog

Since 2.0.5 Introduced.

Code of is serialized: wp-includes/functions.php WP 5.2.4

<?php
function is_serialized( $data, $strict = true ) {
	// if it isn't a string, it isn't serialized.
	if ( ! is_string( $data ) ) {
		return false;
	}
	$data = trim( $data );
	if ( 'N;' == $data ) {
		return true;
	}
	if ( strlen( $data ) < 4 ) {
		return false;
	}
	if ( ':' !== $data[1] ) {
		return false;
	}
	if ( $strict ) {
		$lastc = substr( $data, -1 );
		if ( ';' !== $lastc && '}' !== $lastc ) {
			return false;
		}
	} else {
		$semicolon = strpos( $data, ';' );
		$brace     = strpos( $data, '}' );
		// Either ; or } must exist.
		if ( false === $semicolon && false === $brace ) {
			return false;
		}
		// But neither must be in the first X characters.
		if ( false !== $semicolon && $semicolon < 3 ) {
			return false;
		}
		if ( false !== $brace && $brace < 4 ) {
			return false;
		}
	}
	$token = $data[0];
	switch ( $token ) {
		case 's':
			if ( $strict ) {
				if ( '"' !== substr( $data, -2, 1 ) ) {
					return false;
				}
			} elseif ( false === strpos( $data, '"' ) ) {
				return false;
			}
			// or else fall through
		case 'a':
		case 'O':
			return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
		case 'b':
		case 'i':
		case 'd':
			$end = $strict ? '$' : '';
			return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
	}
	return false;
}

Related Functions

From tag: serialize

More from category: Helper Functions

No comments
    Hello, !     Log In . Register