PHP Serialize for Python

1.3 · maintenance · verified Tue Apr 14

phpserialize is a Python library that ports the `serialize` and `unserialize` functions of PHP, allowing Python applications to encode and decode data in PHP's native serialization format. It implements the standard Python serialization interface, providing `dumps` and `loads` functions. The current version is 1.3, with the last update in 2012, making it in a maintenance phase rather than actively developed, though it officially supports Python 3.

Warnings

Install

Imports

Quickstart

Demonstrates basic serialization and deserialization of strings and PHP arrays. It highlights the necessity of providing byte strings for input to `loads` in Python 3 and handling byte strings for output, or using `decode_strings=True` for automatic string decoding. Also includes an example of deserializing a simple PHP object using `phpobject` as an `object_hook`.

from phpserialize import dumps, loads

# Basic serialization of a string
python_string = 'Hello World'
php_serialized_string = dumps(python_string)
print(f"Serialized string: {php_serialized_string}")
assert loads(php_serialized_string) == b'Hello World'

# Deserialization of a simple PHP array string (as bytes for Python 3)
php_array_data = b'a:1:{s:3:"key";s:5:"value";}'
python_dict = loads(php_array_data)
print(f"Deserialized array: {python_dict}")
# Note: Keys and string values are bytes in Python 3, require decoding
assert python_dict[b'key'] == b'value'

# Deserialization with string decoding
python_dict_decoded = loads(php_array_data, decode_strings=True)
print(f"Deserialized array (decoded): {python_dict_decoded}")
assert python_dict_decoded['key'] == 'value'

# Object serialization example (requires special handling)
# Using a simple PHP object string from a stdClass
php_object_data = b'O:8:"stdClass":1:{s:3:"baz";s:3:"qux";}'
from phpserialize import phpobject
python_obj = loads(php_object_data, object_hook=phpobject, decode_strings=True)
print(f"Deserialized object: {python_obj}")
assert python_obj['baz'] == 'qux'

view raw JSON →