溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

php中序列化與反序列化的示例分析

發(fā)布時(shí)間:2021-08-06 09:39:03 來(lái)源:億速云 閱讀:151 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了php中序列化與反序列化的示例分析,具有一定借鑒價(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中在頁(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是啟用的,那么在向文件中寫入序列化的數(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ù)連接等。

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“php中序列化與反序列化的示例分析”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI