# PHP Serialization

Serialization is the process of converting a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

---

## 1. serialize()
Generates a storable representation of a value. It handles arrays, objects, and scalar types (except resources).

```php
$data = ['apple', 'banana', 'orange'];
$serialized = serialize($data);

echo $serialized;
// Outputs: a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}
```

## 2. unserialize()
Takes a single serialized variable and converts it back into a PHP value.

```php
$original = unserialize($serialized);
print_r($original);
// Outputs the original array
```

## 3. Security Warning (Object Injection)
**Do not pass untrusted user input to `unserialize()`.**

If an attacker can control the string passed to `unserialize()`, they can force the instantiation of arbitrary objects in your application. If these classes define destructors or magic methods like `__wakeup`, they can trigger malicious code execution.

**Alternative:** Use `json_encode()` and `json_decode()` for safer data interchange.

## 4. Magic Methods
Objects can customize their serialization process using magic methods.

*   `__sleep()`: Called before serialization. It is supposed to return an array with the names of all variables of that object that should be serialized.
*   `__wakeup()`: Called after unserialization. It can reconstruct any resources that the object may have.

```php
class Connection {
    public function __sleep() {
        // Close DB connection, return array of properties to save
        return ['dsn', 'username', 'password'];
    }
    public function __wakeup() {
        // Reconnect to DB
    }
}
```

[[programming/php/php]] [[programming/php/php-magic-methods]] [[programming/php/php-json]]