Represent a PHP array as an encoded string

Updated Dani 2 Tallied Votes 228 Views Share

Sometimes we have a need to take a simple PHP array and represent it as an encoded string.

One use case that we have for this at DaniWeb is when a new user signs up, and we ask them to click on a link that was sent to them via email to verify their email address. The URL that they click on has, as a query string parameter, an encoded version of a PHP array that contains information such as the user's ID # and email address. This way, when the user clicks the link, we already know everything we need to about the user and can easily update that user's ID record, without their email address being in plain text in the URL that they click.

Basically what we're doing is converting the array to a JSON string that represents the array contents, then converting that string to a hexidecimal string, and then converting that base 16 string to a base 62 string to condense it (by utilizing A-Za-z0-9).

For example, suppose I have the following PHP array:

$array = array('foo', 'bar', 'baz', 'bat');

This function will convert that array to the simple string 43iGVuUpQisSlw7JnbQyrR8c2AtKX8lCiT.

This also works with associative arrays, multidimensional arrays, etc.

As a reminder, this does not one-way encrypt the string, and it's pretty easy to decode, because it just encodes the string, and doesn't encrypt it. Don't use this for passwords or for anything sensitive!

A good use case is, what we do, which is use it to transport complex data structures via a public-facing URL.

function encode_array(array $array)
{    
    return gmp_strval(gmp_init(bin2hex(json_encode($array)), 16), 62);
}

function decode_array($string = '')
{    
    if (empty($string) OR !ctype_alnum($string))
    {
        return false;
    }

    $new_string = gmp_strval(gmp_init($string, 62), 16);
    
    // Make sure it's a valid hex string
    if (ctype_xdigit($new_string))
    {
        // Decode the hex string
        $object = json_decode(pack("H*", $new_string));
        
        if ($object !== null)
        {
            return $object;
        }
    }    
    
    return false;
}
pritaeas 2,194 ¯\_(ツ)_/¯ Moderator Featured Poster

Nice share. Why not use serialize()/unserialize()?

Dani 4,329 The Queen of DaniWeb Administrator Featured Poster Premium Member

You mean instead of json_encode()? Json_encode and serialize have two different use cases.

Json_encode is the most space efficient way of converting a PHP array to a string.

Serialize is used when you want to transport an object as a string and preserve the object’s properties while in transit. (Eg what type of object is it, the object’s structure, etc.) This way when you unserialize it, it will return back to its original form. Because the string generated contains all this metadata beyond the simple data, the string it produces is much longer.

In my use case, we only need to transport array data.

pritaeas 2,194 ¯\_(ツ)_/¯ Moderator Featured Poster

Ok, space.

The only thing to keep track of then is that your array doesn't exceed 512 levels of depth (insane, I know).

Dani 4,329 The Queen of DaniWeb Administrator Featured Poster Premium Member

Use cases for this would be to transport a tiny bit of data via a URL parameter or the like, so I don’t see that as being a problem.

pritaeas 2,194 ¯\_(ツ)_/¯ Moderator Featured Poster

I think it would be a good use for storing a config file or a cookie (to avoid tampering), as long as there is no need for real encryption.

Dani 4,329 The Queen of DaniWeb Administrator Featured Poster Premium Member

I discovered today that this works wonderfully for the ?state= parameter when using OAuth.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.