Unserialize PHP with Javascript
Abstract
Simply, this is a Javascript library for decoding the output of the PHP serialize() function. It supports the following datatypes:
- Strings
- Integers
- Doubles
- Booleans
- NULL
- Arrays
- Objects
Usage
This is the source of the example.
<?php
/**
* o------------------------------------------------------------------------------o
* | This package is licensed under the Phpguru license. A quick summary is |
* | that for commercial use, there is a small one-time licensing fee to pay. For |
* | registered charities and educational institutes there is a reduced license |
* | fee available. You can read more at: |
* | |
* | http://www.phpguru.org/static/license.html |
* o------------------------------------------------------------------------------o
*
* © Copyright 2008,2009 Richard Heyes
*/
/**
* Escapes a string so it can be safely echo'ed out as Javascript
*
* @param string $str String to escape
* @return string JS Safe string
*/
function EscapeString($str)
{
$str = str_replace(array('\\', "'"), array("\\\\", "\\'"), $str);
$str = preg_replace('#([\x00-\x1F])#e', '"\x" . sprintf("%02x", ord("\1"))', $str);
return $str;
}
$var = array();
foreach ($_SERVER as $k => $v) {
if (strncmp($k, 'HTTP_', 5) == 0) {
$var[$k] = $v;
}
}
$serialized = EscapeString(serialize($var));
?>
<html>
<head>
<title></title>
<script type="text/javascript" language="javascript" src="PHP_Unserialize.js"></script>
<script language="javascript" type="text/javascript">
<!--
toUnserialize = '<?=$serialized?>';
myThing = PHP_Unserialize(toUnserialize);
// -->
</script>
</head>
<body>
<h1>PHP_Unserialize Function</h1>
<b>Results of unserializing $_SERVER HTTP_* PHP variables:</b>
<table border="1" cellspacing="0">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<script language="javascript" type="text/javascript">
<!--
for (i in myThing) {
document.write('<tr><td>' + i + '</td><td>' + myThing[i] + '</td></tr>');
}
// -->
</script>
</table>
</body>
</html>
Example
An example (as shown above) is here.
Caveats
Since PHP5 supports protected and private class members and Javascript doesn't, these are converted into regular public members on the resulting Javascript object.
Also, since the output of the PHP serialize() function can contain characters not normally allowed in a Javascript string literal, it must be escaped first. There's a function (as shown above) in the download that can do this.
Unserialize in other languages
For your perusing leisure, here's a list of unserialize() implementations in other languages courtesy of Yahoo!:
TODO
Naturally, a PHP_Serialize() function would complement this library rather nicely, and not surprisingly, it's in the pipeline.