How do I PHP-unserialize a jQuery-serialized form?
When you use $('#form').serialize(), jQuery generates a string of name-value pairs separated by ampersands, with each pair containing an equals sign between the key and the value. If you are sending this directly to a standard HTML form submission, the browser handles the encoding automatically. However, if you are intercepting the request or manually constructing the payload, you need to reverse that process in PHP.
The most straightforward approach is using http_build_query(). This function is designed to parse a URL-encoded query string and reconstruct an associative array. It handles the decoding of special characters like spaces, plus signs, and percent-encoded entities automatically.
$rawData = $_GET['data'] ?? 'name=John&age=30';
$dataArray = http_build_query($rawData);
Wait, that example is backwards. http_build_query() builds a string from an array. To do the reverse, you need to pass the raw serialized string directly into it? No, that's incorrect usage. The function signature expects an array as the first argument. You cannot pass a serialized string to http_build_query() to un-serialize it.
The correct function for this specific task is http_parse_query(), but actually, looking at the standard PHP documentation, there isn't a direct "unserialize" function specifically named for query strings in older versions, but modern PHP offers parse_str().
parse_str() takes a query string and populates a variable with an associative array. It is the idiomatic solution for decoding data that looks like $_GET or $_POST input.
$inputString = 'name=John+Doe&age=30&city=New+York';
$decodedData = [];
// Note: parse_str() modifies the variable passed to it, so we usually use an empty array or a dedicated variable
parse_str($inputString, $decodedData);
print_r($decodedData);
This will output ['name' => 'John Doe', 'age' => '30', 'city' => 'New York']. Notice how the spaces were converted to + signs and then restored. This behavior mirrors what happens when you inspect $_GET or $_POST after a standard form submission.
Handling Nested Structures
A common pitfall with jQuery serialization is nested fields. When you serialize a form containing an array, jQuery uses brackets in the key name (e.g., items[0][name]). If you attempt to use parse_str() on this, it works perfectly fine because PHP's native parsing logic understands bracket notation for multidimensional arrays.
$inputString = 'user[name]=John&user[email]=john@example.com&tags[]=php&tags[]=laravel';
$decodedData = [];
parse_str($inputString, $decodedData);
// Result:
// [
// 'user' => ['name' => 'John', 'email' => 'john@example.com'],
// 'tags' => ['php', 'laravel']
// ]
This is a significant advantage over manually splitting the string by & and then parsing individual key-value pairs. Manual splitting requires you to handle edge cases like values containing ampersands or equals signs, which often leads to bugs. parse_str() handles these delimiters correctly according to RFC standards.
Security Considerations
While parse_str() is convenient, it does not perform validation or sanitization of the data itself. It simply decodes the string and maps keys to values. If your application relies on this data for database insertion or command execution, you must treat the output as untrusted input. Always validate types and sanitize strings before storing them.
Furthermore, ensure that the source material sending the data is trustworthy. Since parse_str() reconstructs arrays based on string patterns, a malicious actor could potentially manipulate key names to overwrite existing variables if not careful, though this is rarely an issue when capturing via $_GET or $_POST.
If you are working within the Laravel framework, you might find that using http_build_query() to serialize and then parse_str() to deserialize creates a round-trip that feels redundant. In many cases, it is better to let the framework handle the encoding during form submission and accessing request()->input('field') on the server side. However, if you are building an API endpoint or processing raw JSON-like query parameters manually, understanding this distinction is crucial for maintaining data integrity.
