Serialize Detection Function
This function is especially handy for when you’re pulling data from a database and are unsure weather it has been serialized or not.
Simply call the function with the questioned variable as the argument. The function with return either true or false depending on whether the variable has been serialized.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function is_serialized( $data ) { if ( !is_string( $data ) ) return false; $data = trim( $data ); if ( 'N;' == $data ) return true; if ( !preg_match( '/^([adObis]):/', $data, $badions ) ) return false; switch ( $badions[1] ) { case 'a' : case 'O' : case 's' : if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) ) return true; break; case 'b' : case 'i' : case 'd' : if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) ) return true; break; } return false; } |
Example:
1 2 3 | if (is_serialized($data)) { $data = unserialize($data); } |
Source: WordPress
April 1st, 2010 | PHP |