《PHP實戰(zhàn):php中序列化與反序列化詳解》要點:
本文介紹了PHP實戰(zhàn):php中序列化與反序列化詳解,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP實戰(zhàn)把復(fù)雜的數(shù)據(jù)類型壓縮到一個字符串中
PHP實戰(zhàn)serialize() 把變量和它們的值編碼成文本形式
PHP實戰(zhàn)unserialize() 恢復(fù)原先變量
PHP實戰(zhàn)eg:
PHP實戰(zhàn)
$stooges = array('Moe','Larry','Curly');
$new = serialize($stooges);
print_r($new);echo "<br />";
print_r(unserialize($new));
PHP實戰(zhàn)結(jié)果:a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}
PHP實戰(zhàn)Array ( [0] => Moe [1] => Larry [2] => Curly )
PHP實戰(zhàn)當(dāng)把這些序列化的數(shù)據(jù)放在URL中在頁面之間會傳遞時,需要對這些數(shù)據(jù)調(diào)用urlencode(),以確保在其中的URL元字符進(jìn)行處理:
PHP實戰(zhà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>';
PHP實戰(zhàn)margic_quotes_gpc和magic_quotes_runtime配置項的設(shè)置會影響傳遞到unserialize()中的數(shù)據(jù).
PHP實戰(zhàn)如果magic_quotes_gpc項是啟用的,那么在URL、POST變量以及cookies中傳遞的數(shù)據(jù)在反序列化之前必須用stripslashes()進(jìn)行處理:
PHP實戰(zhàn)
$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc開啟
$new_cart = unserialize($cart);
PHP實戰(zhàn)如果magic_quotes_runtime是啟用的,那么在向文件中寫入序列化的數(shù)據(jù)之前必須用addslashes()進(jìn)行處理,而在讀取它們之前則必須用stripslashes()進(jìn)行處理:
PHP實戰(zhàn)
$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'));
PHP實戰(zhàn)在啟用了magic_quotes_runtime的情況下,從數(shù)據(jù)庫中讀取序列化的數(shù)據(jù)也必須經(jīng)過stripslashes()的處理,保存到數(shù)據(jù)庫中的序列化數(shù)據(jù)必須要經(jīng)過addslashes()的處理,以便能夠適當(dāng)?shù)卮鎯?
PHP實戰(zhàn)
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);
PHP實戰(zhàn)當(dāng)對一個對象進(jìn)行反序列化操作時,PHP會自動地調(diào)用其__wakeUp()方法.這樣就使得對象能夠重新建立起序列化時未能保留的各種狀態(tài).例如:數(shù)據(jù)庫連接等.
PHP實戰(zhàn)以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持維易PHP!
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/1811.html