is_serialized() WordPress Function

The is_serialized() function in WordPress checks whether a variable is serialized or not. This is useful when you need to know if a certain string is serialized before performing any actions on it.

is_serialized( string $data, bool $strict = true ) #

Check value to find if it was serialized.


Description

If $data is not an string, then returned value will always be false. Serialized data is always a string.


Top ↑

Parameters

$data

(string)(Required)Value to check to see if was serialized.

$strict

(bool)(Optional) Whether to be strict about the end of the string.

Default value: true


Top ↑

Return

(bool) False if not serialized and true if it was.


Top ↑

More Information

Usage:
is_serialized( $data );
Notes:

Data might need to be serialized to allow it to be successfully stored and retrieved from a database in a form that PHP can understand.


Top ↑

Source

File: wp-includes/functions.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;
}


Top ↑

Changelog

Changelog
VersionDescription
2.0.5Introduced.

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