QA
Intermediate LevelPHP 8+

How do serialize() and unserialize() work with __serialize() and __unserialize() in PHP 7.4+?

❓ Interview Prompt: Explain object byte-string serialization, __serialize / __unserialize magic methods (PHP 7.4+), and security risks of untrusted unserialization.

'serialize()' converts PHP data structures and objects into a storable byte-stream string; 'unserialize()' reconstitutes the original object state.

Modern Custom Serialization (PHP 7.4+):

•
'__serialize(): array': Returns an associative array of properties to serialize.
•
'__unserialize(array $data): void': Re-establishes object state and reconnects resources (e.g. database sockets).

Security Warning:

NEVER run 'unserialize()' on untrusted user input! Unserializing malicious payloads triggers PHP Object Injection / RCE attacks via magic methods. Use 'json_encode()' for user data interchange!

Code Implementation Example

php
<?php
class UserSession {
    public function __construct(public string $username, private string $secretToken) {}

    // PHP 7.4+ Custom Serialization
    public function __serialize(): array {
        return ['username' => $this->username]; // Exclude sensitive secretToken!
    }

    public function __unserialize(array $data): void {
        $this->username = $data['username'];
        $this->secretToken = "regenerated_on_wakeup";
    }
}
💡Custom object serialization using PHP 7.4+ __serialize() and __unserialize() magic methods.
🎯 Interview Key Takeaway

Use __serialize() / __unserialize() for custom object state export. Never unserialize untrusted user input due to RCE risks.

#Serialization#unserialize#Security#Intermediate
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?