首頁  >  文章  >  後端開發  >  php中序列化與反序列化詳解

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

黄舟
黄舟原創
2017-03-07 09:37:031305瀏覽

本文介紹了php中序列化與反序列化的相關知識。具有很好的參考價值,下面跟著小編一起來看下吧

把複雜的資料型別壓縮到一個字串中

##serialize() 把變數和它們的值編碼成文字形式

unserialize() 恢復原先變數

eg:

##
$stooges = array('Moe','Larry','Curly');
$new = serialize($stooges);
print_r($new);echo "<br />";
print_r(unserialize($new));

#結果:a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}

Array ( [0] => Moe [1] => Larry [2] => Curly )

當把這些序列化的資料放在URL中在頁面之間會傳遞時,需要對這些資料呼叫urlencode(),以確保在其中的URL元字元進行處理:

$shopping = array(&#39;Poppy seed bagel&#39; => 2,&#39;Plain Bagel&#39; =>1,&#39;Lox&#39; =>4);
echo &#39;<a href="next.php?cart=&#39;.urlencode(serialize($shopping)).&#39;" rel="external nofollow" >next</a>&#39;;

margic_quotes_gpc和magic_quotes_runtime配置項目的設定會影響傳遞到unserialize()中的資料。

如果magic_quotes_gpc項目是啟用的,那麼在URL、POST變數以及cookies中傳遞的資料在反序列化之前必須用stripslashes()進行處理:

$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc开启
$new_cart = unserialize($cart);

如果magic_quotes_runtime是啟用的,那麼在檔案中寫入序列化的資料之前必須用addslashes()進行處理,而在讀取它們之前則必須用stripslashes()進行處理:

$fp = fopen(&#39;/tmp/cart&#39;,&#39;w&#39;);
fputs($fp,addslashes(serialize($a)));
fclose($fp);
//如果magic_quotes_runtime开启
$new_cat = unserialize(stripslashes(file_get_contents(&#39;/tmp/cart&#39;)));
//如果magic_quotes_runtime关闭
$new_cat = unserialize(file_get_contents(&#39;/tmp/cart&#39;));

在啟用了magic_quotes_runtime的情況下,從資料庫讀取序列化的資料也必須經過stripslashes()的處理,儲存到資料庫中的序列化資料必須經過addslashes()的處理,以便能夠適當地儲存。

mysql_query("insert into cart(id,data) values(1,&#39;".addslashes(serialize($cart))."&#39;)");
$rs = mysql_query(&#39;select data from cart where id=1&#39;);
$ob = mysql_fetch_object($rs);
//如果magic_quotes_runtime开启
$new_cart = unserialize(stripslashes($ob->data));
//如果magic_quotes_runtime关闭
$new_cart = unserialize($ob->data);

當物件進行反序列化操作時,PHP會自動地呼叫其__wakeUp()方法。這樣就使得物件能夠重新建立起序列化時未能保留的各種狀態。例如:資料庫連線等。

 以上就是php中序列化與反序列化詳解的內容,更多相關內容請關注PHP中文網(www.php.cn)!


#

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn