php中序列化與反序列化詳解
把復(fù)雜的數(shù)據(jù)類(lèi)型壓縮到一個(gè)字符串中
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中在頁(yè)面之間會(huì)傳遞時(shí),需要對(duì)這些數(shù)據(jù)調(diào)用urlencode(),以確保在其中的URL元字符進(jìn)行處理:
$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配置項(xiàng)的設(shè)置會(huì)影響傳遞到unserialize()中的數(shù)據(jù)。
如果magic_quotes_gpc項(xiàng)是啟用的,那么在URL、POST變量以及cookies中傳遞的數(shù)據(jù)在反序列化之前必須用stripslashes()進(jìn)行處理:
$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc開(kāi)啟 $new_cart = unserialize($cart);
如果magic_quotes_runtime是啟用的,那么在向文件中寫(xiě)入序列化的數(shù)據(jù)之前必須用addslashes()進(jìn)行處理,而在讀取它們之前則必須用stripslashes()進(jìn)行處理:
$fp = fopen('/tmp/cart','w');
fputs($fp,addslashes(serialize($a)));
fclose($fp);
//如果magic_quotes_runtime開(kāi)啟
$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ù)庫(kù)中讀取序列化的數(shù)據(jù)也必須經(jīng)過(guò)stripslashes()的處理,保存到數(shù)據(jù)庫(kù)中的序列化數(shù)據(jù)必須要經(jīng)過(guò)addslashes()的處理,以便能夠適當(dāng)?shù)卮鎯?chǔ)。
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開(kāi)啟
$new_cart = unserialize(stripslashes($ob->data));
//如果magic_quotes_runtime關(guān)閉
$new_cart = unserialize($ob->data);
當(dāng)對(duì)一個(gè)對(duì)象進(jìn)行反序列化操作時(shí),PHP會(huì)自動(dòng)地調(diào)用其__wakeUp()方法。這樣就使得對(duì)象能夠重新建立起序列化時(shí)未能保留的各種狀態(tài)。例如:數(shù)據(jù)庫(kù)連接等。
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
php的crc32函數(shù)使用時(shí)需要注意的問(wèn)題(不然就是坑)
這篇文章主要介紹了php的crc32函數(shù)使用時(shí)需要注意的問(wèn)題(不然就是坑) ,需要的朋友可以參考下2015-04-04
php中調(diào)用其他系統(tǒng)http接口的方法說(shuō)明
本篇文章主要是對(duì)php中調(diào)用其他系統(tǒng)http接口的方法進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2014-02-02
php使用number_format函數(shù)截取小數(shù)的方法分析
這篇文章主要介紹了php使用number_format函數(shù)截取小數(shù)的方法,結(jié)合實(shí)例形式分析了number_format函數(shù)進(jìn)行浮點(diǎn)數(shù)數(shù)學(xué)運(yùn)算的相關(guān)技巧,需要的朋友可以參考下2016-05-05
PHP Global變量定義當(dāng)前頁(yè)面的全局變量實(shí)現(xiàn)探討
我們?cè)谶@篇文章中就針對(duì)PHP Global變量出現(xiàn)的問(wèn)題給出了一些具體的解決辦法,感興趣的朋友可以參考下哈2013-06-06
PHP 實(shí)現(xiàn)頁(yè)面靜態(tài)化的幾種方法
這篇文章主要介紹了PHP 實(shí)現(xiàn)頁(yè)面靜態(tài)化的幾種方法,需要的朋友可以參考下2017-07-07
利用php+mcDropdown實(shí)現(xiàn)文件路徑可在下拉框選擇
以下是對(duì)php+mcDropdown實(shí)現(xiàn)文件路徑可在下拉框進(jìn)行選擇的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過(guò)來(lái)參考下2013-08-08

