Welcome, guest | Sign In | My Account | Store | Cart

This is a Javascript function that will convert a Javascript array to a string in PHP serialized format. You can pass this string to a PHP script and easily unserialize it to a PHP array.

PHP, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// This is Javascript, not PHP!

function js_array_to_php_array (a)
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can 
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie 
// from PHP like this:
//    <?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?>
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
{
    var a_php = "";
    var total = 0;
    for (var key in a)
    {
        ++ total;
        a_php = a_php + "s:" +
                String(key).length + ":\"" + String(key) + "\";s:" +
                String(a[key]).length + ":\"" + String(a[key]) + "\";";
    }
    a_php = "a:" + total + ":{" + a_php + "}";
    return a_php;
}

I need to pass associative arrays from Javascript running on the client browser to a PHP server-side script. This is very useful for passing complex session state back and forth between Javascript and PHP. PHP has a built-in function to unserialize strings into PHP objects. It is not difficult in Javascript to build strings that can be decoded by the PHP "unserialize()" function. The following is an example of how to decode the string on the PHP side:

Note that the PHP example usage assumes two things. First, it assumes that "magic quotes gpc" is ON in PHP (this is the default). That's why you need to call the "stripslashes()" function in your PHP code. Second, it assumes that you used the Javascript "escape()" function to encode your Cookie before sending it. That's why you need to call the "urldecode()" function in your PHP code.

6 comments

Harry Fuecks 16 years, 3 months ago  # | flag

Multi Byte characters. Be warned that Javascript is "smarter" than PHP when multibyte characters are involved.

SomeString.length

Will tell you the number of characters in a string, no the number of bytes. The example here will only work if the characters in the string are all single byte (i.e. if you may have problems with UTF-8), because PHP's unserialize(), like most PHP string functions, regard 1 char = 1 byte.

Morten Amundsen 16 years, 3 months ago  # | flag

Javascript PHP serializer.

/*
* PHP Serialize
* Morten Amundsen
* mor10am@gmail.com
*/
function php_serialize(obj)
{
    var string = '';

    if (typeof(obj) == 'object') {
        if (obj instanceof Array) {
            string = 'a:';
            tmpstring = '';
            count = 0;
            for (var key in obj) {
                tmpstring += php_serialize(key);
                tmpstring += php_serialize(obj[key]);
                count++;
            }
            string += count + ':{';
            string += tmpstring;
            string += '}';
        } else if (obj instanceof Object) {
            classname = obj.toString();

            if (classname == '[object Object]') {
                classname = 'StdClass';
            }

            string = 'O:' + classname.length + ':"' + classname + '":';
            tmpstring = '';
            count = 0;
            for (var key in obj) {
                tmpstring += php_serialize(key);
                if (obj[key]) {
                    tmpstring += php_serialize(obj[key]);
                } else {
                    tmpstring += php_serialize('');
                }
                count++;
            }
            string += count + ':{' + tmpstring + '}';
        }
    } else {
        switch (typeof(obj)) {
            case 'number':
                if (obj - Math.floor(obj) != 0) {
                    string += 'd:' + obj + ';';
                } else {
                    string += 'i:' + obj + ';';
                }
                break;
            case 'string':
                string += 's:' + obj.length + ':"' + obj + '";';
                break;
            case 'boolean':
                if (obj) {
                    string += 'b:1;';
                } else {
                    string += 'b:0;';
                }
                break;
        }
    }

    return string;
}
Gaetano Giunta 15 years, 6 months ago  # | flag

ATTENTION to security considerations. Aside from the multibyte charcters problem mentioned above, there is a serious vulnerabilty involved in having the PHP server automatically unserializing strings received from the net: if the serialized string contains php object definitions, the PHP engine will call the magic '__wakeup()' function of the given class.

This means that the client is in fact deciding which php code runs on the server, and opens the door to code injection attacks.

So make sure the php string is properly validated before unserializing it on the server!

For more details see eg: http://ilia.ws/archives/107-Another-unserialize-abuse.html

PS: other libs abound that carry out the js-to-php serialization magic, not only on js arrays but on all datatypes, eg: http://sourceforge.net/projects/jpspan

andot 15 years, 5 months ago  # | flag

a best PHP serialize/unserialize implementation for javascript.

Here is a best PHP serialize/unserialize implementation for javascript.

It can serialize/unserialize N,b,i,d,s,U,r,R,a,O,C.

It is included in PHPRPC: http://sourceforge.net/projects/php-rpc/

Stanley Tweedle 13 years ago  # | flag

@#4 -- Thanks for sharing the good ship!

forgive my ignorance, but off-the-top-of-my-head, I'm stumped on what "N,b,i,d,s,U,r,R,a,O,C" is meant to communicate, so i'm curious. Anyone know?

Jayesh Sheth 11 years, 9 months ago  # | flag

You can use json_encode() in PHP 5.2.0 and higher, to achieve something similar. http://us3.php.net/manual/en/function.json-encode.php

Created by Noah Spurrier on Mon, 16 May 2005 (MIT)
PHP recipes (51)
Noah Spurrier's recipes (10)

Required Modules

  • (none specified)

Other Information and Tasks