序列化與反序列化

2021-06-21 16:53:46 字數 1854 閱讀 1643

**:

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

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

unserialize() 恢復原先變數

eg:

$stooges = array('moe','larry','curly');

$new = serialize($stooges);

print_r($new);echo "

";print_r(unserialize($new));

結果: a:3:

array ( [0] => moe [1] => larry [2] => curly )

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

$shopping = array('poppy seed bagel' => 2,'plain bagel' =>1,'lox' =>4);

echo 'urlencode(serialize($shopping)).'">next';

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('/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關閉

$new_cat = unserialize(file_get_contents('/tmp/cart'));

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

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關閉

$new_cart = unserialize($ob->data);

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

序列化和反序列化 C 序列化與反序列化。

序列化介紹 把物件用一種新的格式來表示。系列化只序列化資料。序列化不建議使用自動屬性 為什麼要序列化 將乙個複雜的物件轉換流,方便儲存與資訊交換。class program class person public int age 二進位制序列化 就是將物件變成流的過程,把物件變成byte class...

序列化與反序列化

序列化是將物件處理為位元組流以儲存物件或傳輸到記憶體 資料庫或檔案。其主要目的是儲存物件的狀態,以便可以在需要時重新建立物件。相反的過程稱為反序列化。通過序列化,開發人員可以儲存物件的狀態,並在需要時重新建立該物件,從而提供物件的儲存以及資料交換。通過序列化,開發人員還可以執行類似如下的操作 通過 ...

序列化與反序列化

1 把 物件 轉換為 位元組序列 的過程稱為物件的序列化。把 位元組序列 恢復為 物件 的過程稱為物件的反序列化。序列化using system using system.collections.generic using system.linq using system.text using sy...