PHP序列化與反序列化的使用

2021-07-11 02:36:45 字數 1952 閱讀 4591

序列化:將變數轉化為可儲存或傳輸的字串

反序列化:將該字串在轉化為原來的變數使用

作用:儲存與傳輸資料

這樣說坑定是蒙了。。。。。。

其實說白了就是將陣列改變格式然後存在資料庫(使用json_encode與json_decode也可以),就像是我們儲存全部打包儲存在資料庫中,例子如下:

<?php

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

$new= serialize($arr);

print_r($new);

echo"

";

print_r(unserialize($new));

?>

結果如下:

a:3:

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

應用場景:

頁面跳轉的url傳遞,**如下

<?php 

$shopping = array('haha' => 2,'hehe' =>1,'heihei' =>4);

echo 'next';

$t1 = urlencode(serialize($shopping));

$t2 = urldecode($t1); //將傳過來的資料解析回去

print_r(unserialize($t2));//將傳來的資料解析回去

結果如下:

next

array ( [haha] => 2 [hehe] => 1 [heihei] => 4 )

注:其中next為:

xx/next.php?test=a%3a3%3a%7bs%3a4%3a%22haha%22%3bi%3a2%3bs%3a4%3a%22hehe%22%3bi%3a1%3bs%3a6%3a%22heihei%22%3bi%3a4%3b%7d

你看上面是不是很像我們平時瀏覽的網頁啊

另外注意在margic_quotes_gpc與magic_quotes_runtime開啟的情況下會影響到unnserialize的傳輸,解決辦法如下:

$new_str = unserialize(stripslashes($str));

注:margic_quotes_gpc開啟需要在其反序列化時stripslashes

$fp = fopen('/tmp/str','w');

fputs($fp,addslashes(serialize($a)));

fclose($fp);

//如果magic_quotes_runtime開啟

$new_str = unserialize(stripslashes(file_get_contents('/tmp/str')));

//如果magic_quotes_runtime關閉

$new_str = unserialize(file_get_contents('/tmp/str'));

注:如果

magic_quotes_runtime開啟需要在寫入檔案前addslashes()處理,讀取時stripslashes()處理

php序列化與反序列化

php的序列化 反序列化對與一些大檔案的壓縮操作,讀寫操作十分有用。乙個簡單的序列化案例 同時用到了序列化與反序列化函式,二者在被呼叫時會分別自己呼叫對應的函式,sleep 以及 wakeup.sleep和 wakeup練習題 故事 乙個果農生產了很多水果種類,於是需要把乙個買家指定的種類寄給他,生...

php 序列化與反序列化

序列化 反序列化序列化 例一class user number 66 str jerry bool true null null arr array a 1,b 2 user new user tom true var dump serialize number var dump serialize...

php序列化與反序列化

jarvisoj上的一道題 是關於php序列化以及反序列化引起的問題,我看 wp大神的wp 題目給直接給出了源 這句話是關鍵,漏洞產生在php serialize和php解析方式上。如果我們通過php serialize的方式構造序列化語句,然後通過php的方式解析序列化語句,就會出現問題。原因是在...