ActiveState Code

Recipe 414334: Pass Javascript arrays to PHP


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
 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;
}

Discussion

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.

Comments

  1. 1. At 10:05 a.m. on 26 aug 2005, Harry Fuecks said:

    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.

  2. 2. At 2:25 a.m. on 31 aug 2005, Morten Amundsen said:

    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;
    }
    
  3. 3. At 1:44 a.m. on 23 may 2006, Gaetano Giunta said:

    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

  4. 4. At 11:30 a.m. on 19 jun 2006, Anonymous said:

    a best PHP serialize/unserialize implementation for javascript. http://www.coolcode.cn/?p=171

    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/project/showfiles.php?group_id=163368

  5. 5. At 8:48 a.m. on 26 nov 2008, Stanley Tweedle said:

    @#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?

Sign in to comment