今天在修Bug時,發現到一個問題,在PHP常常會用到 serialize() & unserialize() 這個函式,但是假如今天存進去的資料格式不正確,要如何驗證資料的正確性真且安全的反解出來,我今天就遇到了這個"Notice: unserialize(): Error at offset 0 of 63 bytes "的訊息,代表資料格式不正確,無法正確的反解資料,於是我去PHP官網找到了別人寫的一個function。
function safe_unserialize($serialized) {
// unserialize will return false for object declared with small cap o
// as well as if there is any ws between O and :
if (is_string($serialized) && strpos($serialized, "\0") === false) {
if (strpos($serialized, 'O:') === false) {
// the easy case, nothing to worry about
// let unserialize do the job
return @unserialize($serialized);
} else if (!preg_match('/(^|;|{|})O:[0-9]+:"/', $serialized)) {
// in case we did have a string with O: in it,
// but it was not a true serialized object
return @unserialize($serialized);
}
}
return false;
}