ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Pass Javascript arrays to PHP
Submitter: Noah Spurrier (other recipes)
Last Updated: 2005/05/16
Version no: 1.0
Category: Session Management

 

5 stars 2 vote(s)


Description:

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.

Source: Text Source

// 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.



Add comment

Number of comments: 4

Multi Byte characters, Harry Fuecks, 2005/08/26
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.
Add comment

Javascript PHP serializer, Morten Amundsen, 2005/08/31


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





Add comment

ATTENTION to security considerations, Gaetano Giunta, 2006/05/23
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
Add comment

a best PHP serialize/unserialize implementation for javascript, Not specified Not specified, 2006/06/19
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
Add comment



Highest rated recipes:

1. DB_eSession PHP class ...

2. iPHP: Semi-interactive ...

3. main - python-like if ...

4. Microsoft Access ...

5. tinySendMail

6. Single Linked List

7. PHP MySQL Search Class

8. Pass Javascript arrays ...

9. Microsoft Access ...

10. Password generation




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.