📜  如何使用PHP serialize() 和 unserialize()函数(1)

📅  最后修改于: 2023-12-03 15:38:07.236000             🧑  作者: Mango

使用 PHP serialize() 和 unserialize() 函数

PHP serialize() 和 unserialize() 函数用于将数据转换为可存储或可传输的格式,并在需要时进行反序列化。

serialize()

serialize() 函数接受一个任意的 PHP 值并返回其字符串表示。这个字符串表示包含 PHP 变量的类型和值。它可以用于将数据存储在文件或数据库中,或将数据传输给其他 PHP 应用程序。

以下是一些使用 serialize() 函数的示例:

// 数组序列化
$data = array('name' => 'John', 'age' => 30, 'city' => 'New York');
$serialized_data = serialize($data);
echo $serialized_data; // 输出: "a:3:{s:4:"name";s:4:"John";s:3:"age";i:30;s:4:"city";s:8:"New York";}"

// 对象序列化
class Person {
    public $name;
    public $age;
    public $city;
    function __construct($name, $age, $city) {
        $this->name = $name;
        $this->age = $age;
        $this->city = $city;
    }
}
$person = new Person('John', 30, 'New York');
$serialized_person = serialize($person);
echo $serialized_person; // 输出: "O:6:"Person":3:{s:4:"name";s:4:"John";s:3:"age";i:30;s:4:"city";s:8:"New York";}"

// 序列化多个值
$data1 = 'Hello';
$data2 = 123;
$serialized_data = serialize(array($data1, $data2));
echo $serialized_data; // 输出: "a:2:{i:0;s:5:"Hello";i:1;i:123;}"
unserialize()

unserialize() 函数接受一个字符串并将其转换回 PHP 值。这个字符串表示必须由 serialize() 函数生成。

以下是一些使用 unserialize() 函数的示例:

// 数组反序列化
$serialized_data = 'a:3:{s:4:"name";s:4:"John";s:3:"age";i:30;s:4:"city";s:8:"New York";}';
$data = unserialize($serialized_data);
print_r($data); // 输出: Array ( [name] => John [age] => 30 [city] => New York )

// 对象反序列化
$serialized_person = 'O:6:"Person":3:{s:4:"name";s:4:"John";s:3:"age";i:30;s:4:"city";s:8:"New York";}';
$person = unserialize($serialized_person);
print_r($person); // 输出: Person Object ( [name] => John [age] => 30 [city] => New York )

// 反序列化多个值
$serialized_data = 'a:2:{i:0;s:5:"Hello";i:1;i:123;}';
$data = unserialize($serialized_data);
print_r($data); // 输出: Array ( [0] => Hello [1] => 123 )

需要注意的是,使用 unserialize() 函数时需要确保反序列化的数据是安全的,以避免 PHP Object Injection 攻击。