把復(fù)雜的數(shù)據(jù)類型壓縮到一個字符串中
serialize() 把變量和它們的值編碼成文本形式
unserialize() 恢復(fù)原先變量
eg:
$stooges = array('Moe','Larry','Curly');$new = serialize($stooges);print_r($new);echo "<br />";print_r(unserialize($new));結(jié)果:a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}
Array ( [0] => Moe [1] => Larry [2] => Curly )
當(dāng)把這些序列化的數(shù)據(jù)放在URL中在頁面之間會傳遞時,需要對這些數(shù)據(jù)調(diào)用urlencode(),以確保在其中的URL元字符進行處理:
$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);echo '<a href="next.php?cart='.urlencode(serialize($shopping)).'" rel="external nofollow" >next</a>';margic_quotes_gpc和magic_quotes_runtime配置項的設(shè)置會影響傳遞到unserialize()中的數(shù)據(jù)。
如果magic_quotes_gpc項是啟用的,那么在URL、POST變量以及cookies中傳遞的數(shù)據(jù)在反序列化之前必須用stripslashes()進行處理:
$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc開啟$new_cart = unserialize($cart);
如果magic_quotes_runtime是啟用的,那么在向文件中寫入序列化的數(shù)據(jù)之前必須用addslashes()進行處理,而在讀取它們之前則必須用stripslashes()進行處理:
$fp = fopen('/tmp/cart','w');fputs($fp,addslashes(serialize($a)));fclose($fp);//如果magic_quotes_runtime開啟$new_cat = unserialize(stripslashes(file_get_contents('/tmp/cart')));//如果magic_quotes_runtime關(guān)閉$new_cat = unserialize(file_get_contents('/tmp/cart'));在啟用了magic_quotes_runtime的情況下,從數(shù)據(jù)庫中讀取序列化的數(shù)據(jù)也必須經(jīng)過stripslashes()的處理,保存到數(shù)據(jù)庫中的序列化數(shù)據(jù)必須要經(jīng)過addslashes()的處理,以便能夠適當(dāng)?shù)卮鎯Α?/p>
mysql_query("insert into cart(id,data) values(1,'".addslashes(serialize($cart))."')");$rs = mysql_query('select data from cart where id=1');$ob = mysql_fetch_object($rs);//如果magic_quotes_runtime開啟$new_cart = unserialize(stripslashes($ob->data));//如果magic_quotes_runtime關(guān)閉$new_cart = unserialize($ob->data);當(dāng)對一個對象進行反序列化操作時,PHP會自動地調(diào)用其__wakeUp()方法。這樣就使得對象能夠重新建立起序列化時未能保留的各種狀態(tài)。例如:數(shù)據(jù)庫連接等。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持VeVb武林網(wǎng)!
新聞熱點
疑難解答
圖片精選