Turning a var_dump, print_r or serialized blob back into data, without eval() or unserialize()
A customer reports a failed checkout. The log has the answer: somebody, years ago, left a var_dump($order) in the error handler, and there it is, forty lines of array(3) { and string(6) "WID-01". You want that order as JSON to send to the payments team, or as a PHP array to drop into a test. Or the problem is a WordPress site that lost its widgets after a domain move, and the culprit is a single option_value that starts a:12:{s:5: and goes on for three screens.
Both are data. Neither is in a format anything outside PHP reads, and the quickest ways of reading them back inside PHP are exactly the ones you shouldn't use. This post explains what PHP's four formats keep and lose, why eval() and unserialize() are the wrong tools, and how the JSON / CSV / PHP Converter reads them instead.
Four formats, four jobs
PHP has four built-in ways of turning a value into text, and they were designed for different readers. That's why each throws away something different.
| Function | Written for | Keeps types? | Keeps class names? | Valid PHP? |
|---|---|---|---|---|
var_dump() | A developer debugging | Yes, plus string lengths | Yes | No |
print_r() | A human skimming | No | Yes | No |
var_export() | Pasting back into code | Yes | Via __set_state() | Yes |
serialize() | Storing and reading back | Yes, plus byte lengths | Yes | No |
var_dump(): everything, verbosely
var_dump() prints every value with its type: int(1017), bool(false), string(6) "WID-01", float(19.5). Arrays show their element count, objects their class and an instance number. It's the most complete of the debug formats, which makes it the best one to find in a log. The complication is Xdebug, which many development setups load: it replaces var_dump() with its own layout, with a file.php:42: line on top, 'key' => instead of ["key"]=>, class Item#7 instead of object(Item)#7, and double for floats. A log can contain either, depending on which machine wrote it.
print_r(): readable, and lossy
print_r() prints scalars as plain text and nothing else. true becomes 1; false and null become nothing at all; the integer 1 and the string "1" look identical. That's fine for skimming and a problem for reading back: from [deleted] => with nothing after it, no program can tell whether the value was false, null or an empty string. The information isn't hidden. It was never written.
var_export(): code
var_export() writes a PHP expression that rebuilds the value: ['order' => 1017, 'paid' => false]. It is the only one of the four that's valid PHP, which is both its strength and, as below, the trap.
serialize(): storage, with byte counts
serialize() is compact and complete: a:2:{s:4:"name";s:5:"Café";s:1:"n";i:1;}. Every string carries its length in bytes, not characters (the é in Café takes two bytes in UTF-8, so Café is s:5). Objects carry their class name, and repeated objects and PHP references are written as back-references (r: and R:). WordPress stores options, widget settings and post meta this way, and so do many PHP caches and session handlers.
The obvious way back is the dangerous one
PHP has a function that reads each of the formats you'd most like to read back. Using them on text you didn't produce yourself is a mistake, and on text from anyone else it's a security hole.
eval() runs whatever is there
Since var_export() output is PHP, the quick way to get the array back is eval('return ' . $text . ';'). That works on a value you exported yourself a minute ago. On text from a ticket, a forum post, a colleague's paste or a log line that includes user input, it runs whatever the text contains. ['a' => system('rm -rf ~')] is a perfectly valid array literal as far as eval() is concerned.
unserialize() builds objects, and objects run code
unserialize() is subtler. It doesn't run arbitrary code, but it does create objects of whatever class the data names, with whatever property values the data says, and it calls the methods PHP calls on those objects as they come to life and as they are destroyed: __unserialize() or __wakeup() straight away, __destruct() later. If any class loaded in the application does something interesting in those methods (deletes a file named in a property, writes a log to a path, calls a callback), an attacker who controls the serialized text controls that behaviour. Chains of such classes in popular libraries, called gadget chains, have turned unserialize() on user input into remote code execution many times. The PHP manual says plainly not to pass untrusted input to it, even with its allowed_classes option.
There's a practical problem too: even when the data is harmless, unserialize() needs the classes it names. Data from another application, or from a plugin you don't have installed, either fails or turns into __PHP_Incomplete_Class objects that are awkward to look inside.
And the other two formats have no reader at all
PHP has no function that reads var_dump() or print_r() output back. People write regular expressions, which break on the first string that contains a line break or a =>.
Reading without running
The converter reads all four PHP formats, plus JSON, XML, CSV, YAML and query strings, with parsers that only ever recognise data.
- PHP array code is split into tokens by PHP's own tokenizer and then read by a small parser that accepts literals and nothing else: arrays in either syntax, strings, numbers,
true,false,null,(object)and(array)casts,stdClass::__set_state(), strings joined with a dot, and a few constants such asPHP_INT_MAXandPHP_EOL. A function call is an error, not an action: paste['a' => system('id')]and the answer is thatsystemcan't be read and only literal values are allowed. - serialize() data is read by a parser of its own that walks the text, never calling
unserialize(). Objects of any class become plain objects (stdClass), so no class is ever loaded or instantiated and no magic method can run. Private and protected properties, whichserialize()marks with hidden NUL-byte prefixes, come back under their plain names. Back-references are resolved, and a reference to a value that contains itself is refused. The two forms it can't read without the original classes are custom serialization (C:) and enums (E:), which give a clear error. - var_dump() is read in both PHP's and Xdebug's layout, file-and-line header included, and print_r() in its usual indented form.
Everything lands in one in-between value, the same thing PHP itself would hold in memory, and is written back out in the format you pick. That's what makes every direction possible, including a format to itself.
Where the work happens. The parsing runs on this site's server: the page posts what you paste and shows the reply. Nothing is executed, but the text is sent, so think twice before pasting a dump full of customers' personal data, and see the privacy policy.
A worked example: a var_dump from a log
Here is a dump of the kind Xdebug writes to a log, with an object inside and a null at the end:
/var/www/app/src/Checkout.php:42:
array(3) {
'order' =>
int(1017)
'paid' =>
bool(false)
'items' =>
array(2) {
[0] =>
class Item#7 (2) {
public $sku =>
string(6) "WID-01"
protected $price =>
double(19.5)
}
[1] =>
NULL
}
}
Pasted into the converter, it's detected as var_dump() without being told. Converted to JSON, it comes out as:
{
"order": 1017,
"paid": false,
"items": [
{
"sku": "WID-01",
"price": 19.5
},
null
]
}
Every type survived: 1017 is a number, false is a boolean, the null is a null. The Item object became a plain JSON object, and its protected $price a normal key. Switch the output to PHP array and the same data comes out as short-syntax array code ready for a test fixture, with 'order' => 1017 and 'paid' => false.
Try the same with a print_r() of a record whose deleted flag was false and whose note was null, and both come back as empty strings, because that's all print_r() wrote down. If your logs use print_r(), switch them to var_export() or json_encode(): whoever reads them next will thank you.
Formats that have no types, and the guesses they force
Four of the nine formats, print_r(), CSV, XML and query strings, store every value as text. Converting them to JSON or PHP means deciding what's a number, and every rule surprises someone.
The converter's rule for print_r() and CSV
Text that looks exactly as PHP would print a whole number or a decimal becomes a number; everything else stays text. So 42 and -3 become integers and 1.5 a float, while 007, 1e5 and +5 stay strings, because turning them into numbers would change what's written. Two consequences worth knowing:
- A decimal written with trailing zeros, such as
1.50, becomes the number1.5. Fine for amounts you'll calculate with; not what you want for a price you'll display. - One column can end up with mixed types. In a CSV of postcodes,
007stays a string and10115becomes a number. If the consumer of your JSON is strict about types, check those columns.
XML: the shape depends on the count
XML is read the way PHP's SimpleXML reads it, and so has SimpleXML's best-known quirk: one <x> element becomes a single value, two become a list. <r><x>1</x></r> gives {"x": "1"} and <r><x>1</x><x>2</x></r> gives {"x": ["1", "2"]}. Code that consumes the JSON has to expect both. Entities are never expanded and nothing is fetched from the network, so an XML file can't make the server read a local file or call a URL.
Query strings: what $_GET sees
Query strings are read with PHP's own parse_str(), so the result is exactly what a PHP script would find in $_GET, quirks included. Every value is a string. Brackets build arrays (b[]=2&b[]=3, c[k]=v). And PHP turns dots and spaces in parameter names into underscores, so a.b=1 arrives as a_b. That's a classic source of "the parameter is in the URL but my script can't see it", and seeing the converted result is a quick way to spot it.
JSON: very large integers
JSON is read with json_decode(), so an integer larger than PHP's integer range (above 9,223,372,036,854,775,807 on 64-bit systems) becomes a floating-point number and loses its last digits. IDs from systems that use 64-bit unsigned or larger identifiers are the usual victims; if you need them exact, they should be strings in the JSON to begin with.
Serialized data that won't load
The byte counts in serialize() output are what make WordPress options fragile. A search-and-replace over a database dump that changes http:// to https://, or one domain to a longer one, changes the text but not the count in front of it, and unserialize() then rejects the whole value. Accented characters cause the same thing when something counts characters instead of bytes. The tool's page guide walks through the repair step by step; the mechanics are worth knowing too.
When the parser reads s:4:", it first checks whether the string really ends four bytes later with ";. If it does, all is well. If it doesn't, it doesn't give up: it looks for the first "; that is followed by something serialized data can continue with (another value, a closing brace, or the end of the text), takes that as the real end, and carries on. When you then convert to serialize(), the output is written fresh, so every length is counted again. In practice, a:2:{s:4:"name";s:4:"Café";s:1:"n";i:1;}, with the length counted in characters, comes out as a:2:{s:4:"name";s:5:"Café";s:1:"n";i:1;}.
Two things to watch:
- Objects. Objects as arrays is ticked by default, which turns objects into arrays in the PHP outputs. When repairing a value that holds objects, untick it. Even then the objects come back as
stdClass, since the parser never learns their real classes, so a plugin that expects its own class in that option may not accept the repaired value. Plain arrays of strings and numbers, which is what most options are, round-trip cleanly. - Strings that contain
";followed by something that looks like serialized data can, rarely, fool the repair into ending a string too early. Convert to JSON first and check that the values read as you expect before pasting anything back into a database.
Limits worth knowing
- Input is limited to 2 MB per conversion.
- PHP array input must be literal: no variables, function calls, heredocs or strings with
$variablesin them. - Class names aren't kept. Objects come back as
stdClass, or as arrays with Objects as arrays ticked. - Formats without types can't give back types that were never written:
print_r()'sfalseandnullare gone for good. - Format detection is a guess from how the text starts. When text could be read two ways (a single line that is both a CSV row and a query string, say), pick the input format yourself.
Practical tips
- Log with
var_export()orjson_encode(), notprint_r(), if anyone might need to read the data back. - Never
eval()orunserialize()text you didn't write, in your own code as much as anywhere else. If you must store PHP values from users, store JSON. - Check a round trip with Swap. Convert, then press the swap button to convert the result back; if it doesn't come back the same, something in the source format couldn't be represented.
- Repair serialized data on a copy, and keep the original value until the site reads the repaired one correctly.
- Use the URL trick for query strings: paste a whole URL and you see its parameters exactly as PHP's
$_GETwill, underscores and all.