nhuff717
nhuff717

Reputation: 369

How do I get PHP to properly URL encode a numerically indexed array?

I have a PHP service that pulls in POST data from the client like so:

if($_POST['data']) {
    $uid = $_POST['data'][0];
    $cid = $_POST['data'][1];
    // ...
}

The client sends URL encoded POST data like this:

'data%5B%5D=58&data%5B%5D=17'

Client Javascript passes an array to form the above string:

var data = [58,17];

Now I'm writing another PHP script where I want to call the former service from within PHP using cURL. However, the following attempts to properly URL encode this simple array are not creating the format that I know the client sends:

// Valid, expected URL encoded result
echo "<pre>data%5B%5D=58&data%5B%5D=17</pre>";

// User-submitted function from PHP.net
// that's supposed to do it right, but doesn't
function cr_post($a, $b = '', $c = 0) {
    if (!is_array($a)) return false;

    foreach ((array)$a as $k=>$v) {
        if($c) {
            if(is_numeric($k)) {
                $k = $b."[]";
            } else {
                $k = $b."[$k]";
            }
        } else if (is_int($k)) {
            $k = $b.$k;
        }

        if(is_array($v)||is_object($v)) {
            $r[] = cr_post($v,$k,1);
            continue;
        }

        $r[] = urlencode($k)."=".urlencode($v);
    }

    return implode("&",$r);
}

echo '<pre>'.cr_post(array(58,17)).'</pre>'; // Outputs '0=58&1=17' incorrectly

// Another attempt
$data = array(58,17);
$query = http_build_query($data);
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);

echo '<pre>'.$query.'</pre>'; // Outputs '0=58&1=17' incorrectly

Is there a better or easier way to do this? What's wrong with my approach?

Upvotes: 1

Views: 478

Answers (1)

shudder
shudder

Reputation: 2101

You were close at second attempt:

$data = array(58,17);
//equivalent to $string = 'data%5B0%5D=58&data%5B1%5D=17';
$string = http_build_query(array('data' => $data));

You could strip those numeric indexes with preg_replace, but I would try if it changes anything first.

Upvotes: 2

Related Questions