Zend Certified Engineer

phpguru.org

Free PHP, Javascript and C# code

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 dual licensed as GPL and a commercial license.               |
    * | If you use the code commercially (or if you don't want to be restricted by   |
    * | the GPL license), you will need the commercial license. It's only £49 (GBP - |
    * | roughly $98 depending on the exchange rate) and helps me out a lot. Thanks.  |
    * o------------------------------------------------------------------------------o
    *
    * © Copyright 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.

Link to me

If you use any of the code on this site (and if you don't I guess) or it makes your life easier, I'd appreciate a link - http://www.phpguru.org. Thanks.

RSS Feed for Comments

Comments

Author: Joshua Eichorn
Posted: 26th February 2006 23:10
First I would say that using JSON for something like this is a much better plan. Its going to be supported by a C extenstion by default in at least PHP6, and already has a C and PHP implementation today.

That being said some HTML_AJAX dev's wanted to do the same thing, so there is a PHP unserialize and serialize implementation in HTML_AJAX.

http://websvn.bluga.net/wsvn/HTML_AJAX/trunk/js/serializer/phpSerializer.js?op=file&rev=0&sc=0
Quote
Author: Richard Heyes
Posted: 26th February 2006 23:22
Joshua Eichorn:
> First I would say that using JSON for something
> like this is a much better plan. Its going to
> be supported by a C extenstion by default in at
> least PHP6, and already has a C and PHP
> implementation today.

Tomato, tomatoe. The end result is the same.

> That being said some HTML_AJAX dev's wanted to
> do the same thing, so there is a PHP
> unserialize and serialize implementation in
> HTML_AJAX.

Here again it's being suggested (see RPC article and comment about PEAR::XMLRPC2) to use code which has been given a version number lower than than the number of seconds it takes light from my lamp to reach my eyes.

If this code works, and has been well tested, then it deserves a decent version number, otherwise it is suggestive that it's either alpha or beta quality, and thus shouldn't be used in production.
Quote
Author: Michael Phipps
Posted: 27th February 2006 07:57
Perhaps I'm just not thinking straight - but what can you do with this script? It's not clear why you would use this rather than unserializing the data in php first.

I'm probably missing something quite obvious.
Quote
Author: Richard Heyes
Posted: 27th February 2006 09:24
Michael Phipps:
> Perhaps I'm just not thinking straight - but
> what can you do with this script? It's not
> clear why you would use this rather than
> unserializing the data in php first.
>
> I'm probably missing something quite obvious.

You can use it to pass data structures between PHP and Javascript. Eg, you have an array that you want to use in Javascript. You can serialize it in PHP, echo the string out in your page, unserialize it, and use it.
Quote
Author: andr3a
Posted: 11th May 2006 15:46
JavaScript PHP_Serializer , sounds good ? :-)
http://www.devpro.it/javascript_id_102.html
Quote
Author: Saravanan
Posted: 26th May 2006 05:45
Could you help me that how to call the php function into the html tag?

<?
function abc()
{
echo "hello";
}

echo '<html><body>';
echo '<input type=button name=b value=click onclick="abc()">';
echo '</body></html>';
?>

Thanks and regards,
Saravanan
Quote
Author: Saravanan
Posted: 26th May 2006 05:51
Could you help me that how to call the php function into the html tag?

<?
function abc()
{
echo "hello";
}
?>

<html><body>
<input type=button name=b value=click onclick="<? abc() ?>">
</body></html>
Quote
Author: lckheng
Posted: 4th June 2006 06:53
<html>
<head>
<script language="javascript">
function funcClick(name){
<?php
$phpName = name; //here problem..
?>
htxtname.value = <?php echo $phpName; ?>;
}
</script>
</head>
<body>
<input type="text" id="htxt" name="htxt">
<input type="button" id="hbtn" name="hbtn" value="click" onlick="funcClick('lckheng');">
</body>
</html>

this is for example...
i wanna assign the parameter to php's variable..if i use the javascript function...
Quote
Author: andot
Posted: 20th June 2006 07:22
http://www.coolcode.cn/wp-content/plugins/coolcode/coolcode.php?p=171&download=phpserializer.js

This is a complete version.
Quote
Author: Ozmo
Posted: 14th August 2006 01:20
Seems great, however doesn't work with arrays of arrays.


$myPerson = array(
'name' => array(
'first' => 'FIRSTNAME',
'last' => 'LASTNAME'
),
);

Outputs name, and blank on the right side when using the example page. Single scalars work.
Quote
Author: Richard Quadling
Posted: 19th March 2008 13:05
http://www.phpguru.org/static/PHP_Unserialize.html

Warning: highlight_file(./downloads/PHP_Unserialize/PHP_Unserialize.php) [function.highlight-file]: failed to open stream: No such file or directory in /home/www/www.phpguru.org/templates/static/PHP_Unserialize.html on line 37

Warning: highlight_file() [function.highlight-file]: Failed opening './downloads/PHP_Unserialize/PHP_Unserialize.php' for highlighting in /home/www/www.phpguru.org/templates/static/PHP_Unserialize.html on line 37
Quote
Author: Richard Heyes
Posted: 19th March 2008 13:10
Richard Quadling:
> http://www.phpguru.org/static/PHP_Unserialize.html
>
> Warning:
> highlight_file(./downloads/PHP_Unserialize/PHP_Unserialize.php)
> [function.highlight-file]: failed to open
> stream: No such file or directory in
> /home/www/www.phpguru.org/templates/static/PHP_Unserialize.html
> on line 37
>
> Warning: highlight_file()
> [function.highlight-file]: Failed opening
> './downloads/PHP_Unserialize/PHP_Unserialize.php'
> for highlighting in
> /home/www/www.phpguru.org/templates/static/PHP_Unserialize.html
> on line 37

Oh dear. Guess I must have moved it.
Quote
Author: Adolf Hartsenberg
Posted: 21st April 2008 20:34
Hi,
(Thank you) * 10g
I've been searching the web for more than 16 hours to find a solution. your's is right on target for my purpose.

I use it to return a complex result from php via sajax to the client for updating a form (so to save time refreshing the whole form.

Only thing I must still find out is: what happens if the php:array is populated with funny chars from a database as in real life we developers do not have control over user input.

Best regards

Adolf (ZA)
Quote
Author: Richard Heyes
Posted: 21st April 2008 20:39
> Only thing I must still find out is: what
> happens if the php:array is populated with
> funny chars from a database as in real life we
> developers do not have control over user
> input.

Don't know - try it and see.
Quote
Author: Adolf Hartsenberg
Posted: 21st April 2008 22:49
Ozmo:
> Seems great, however doesn't work with arrays of
> arrays.
>
>
> $myPerson = array(
> 'name' => array(
> 'first' =>
> 'FIRSTNAME',
> 'last' => 'LASTNAME'
> ),
> );
>
> Outputs name, and blank on the right side when
> using the example page. Single scalars work

I have used it like that and it worked.
Here is my array:

$Students = array();
$students[] = array("name" => "Tom", "age" => 27);
$students[] = array("name" => "George", "age" => 32);
return EscapeString(serialize($students));

Hope it helps!
Quote
Author: Adolf Hartsenberg
Posted: 21st April 2008 22:57
Richard Heyes:
> > Only thing I must still find out is: what
> > happens if the php:array is populated with
> > funny chars from a database as in real life
> we
> > developers do not have control over user
> > input.
>
> Don't know - try it and see.

Hooray, it works, even with funny chars in strings!
Quote

Post Comment

Your name:
Your email:
(Don't worry, I won't spam you. Also, if you do put your email address in here, you'll get notified of new comments. If you don't, you won't.)
Comments:
  Do not post support type questions please

 
CAPTCHA image If you can't read the CAPTCHA then press the submit button to get another. Your comment will re-appear (as if by magic...).
Captcha image
Last modified: 16:48 29th December 2006