欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php中序列化與反序列化詳解

 更新時(shí)間:2017年02月13日 16:40:18   作者:不想下天橋  
本文介紹了php中序列化與反序列化的相關(guān)知識(shí)。具有很好的參考價(jià)值,下面跟著小編一起來看下吧

把復(fù)雜的數(shù)據(jù)類型壓縮到一個(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中在頁面之間會(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開啟
$new_cart = unserialize($cart);

如果magic_quotes_runtime是啟用的,那么在向文件中寫入序列化的數(shù)據(jù)之前必須用addslashes()進(jìn)行處理,而在讀取它們之前則必須用stripslashes()進(jì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'));

在啟用了magic_quotes_runtime的情況下,從數(shù)據(jù)庫中讀取序列化的數(shù)據(jù)也必須經(jīng)過stripslashes()的處理,保存到數(shù)據(jù)庫中的序列化數(shù)據(jù)必須要經(jīng)過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開啟
$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ù)庫連接等。

以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!

相關(guān)文章

最新評(píng)論