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

2022-10-06 00:15:25 字數 1883 閱讀 3948

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

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

unserializ程式設計客棧e() 恢復原先變數

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

$new = serialize($stooges);

print_r($new);eiqdaxmcho "

iqdaxmt;";

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 'php?cart='.urlencode(serialize($shopping)).'" rel="external nofollow" >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 = uns程式設計客棧erialize(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()方法。這樣就使得物件能夠重新建立起序列化時未能保留的各種狀態。例如:資料庫連線等。

本文標題: php中序列化與反序列化詳解

本文位址:

php中序列化與反序列化

把複雜的資料型別壓縮到乙個字串中 serialize 把變數和它們的值編碼成文字形式 unserialize 恢復原先變數 eg stooges array moe larry curly new serialize stooges print r new echo print r unserial...

php中序列化與反序列化

把複雜的資料型別壓縮到乙個字串中 serialize 把變數和它們的值編碼成文字形式 unserialize 恢復原先變數 eg stooges array moe larry curly new serialize stooges print r new echo print r unserial...

php中序列化與反序列化

把複雜的資料型別壓縮到乙個字串中 serialize 把變數和它們的值編碼成文字形式 unserialize 恢復原先變數 eg stooges array moe larry curly new serialize stooges print r new echo print r unserial...