maybe_serialize() WordPress Function
maybe_serialize() is a utility function for safely storing data in a way that can be retrieved and unserialized later. This is useful for storing data in a database or other storage mechanism that does not support complex data types like arrays or objects. Serialization is the process of converting data into a format that can be stored and later reconstructed. When data is serialized, it is converted into a string representation. This string can then be stored in a database or other storage mechanism. The maybe_serialize() function takes a variable and serializes it if it is not already serialized. If the variable is already serialized, the function returns the variable unchanged. This function is useful for ensuring that data is stored in a consistent format.
maybe_serialize( string|array|object $data ) #
Serialize data, if needed.
Parameters
- $data
(string|array|object)(Required)Data that might be serialized.
Return
(mixed) A scalar data.
More Information
- 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.
- Confusingly, strings that contain already serialized values are serialized again, resulting in a nested serialization. Other strings are unmodified.
- A possible solution to prevent nested serialization is to check if a variable is serialized using is_serialized()
if( !is_serialized( $data ) ) { $data = maybe_serialize($data); }
Source
File: wp-includes/functions.php
function maybe_serialize( $data ) { if ( is_array( $data ) || is_object( $data ) ) { return serialize( $data ); } /* * Double serialization is required for backward compatibility. * See https://core.trac.wordpress.org/ticket/12930 * Also the world will end. See WP 3.6.1. */ if ( is_serialized( $data, false ) ) { return serialize( $data ); } return $data; }
Expand full source codeCollapse full source codeView on TracView on GitHub
Changelog
Version | Description |
---|---|
2.0.5 | Introduced. |