Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP build query with PHP_QUERY_RFC3986 before PHP 5.4

Tags:

http

php

I thought I would be able to use the easy http_build_query to encode some GET parameters from an array, but apparently the enc_type seems to have been added in PHP 5.4. Unfortunately I'm on PHP 5.3.10.

Problem is that I need the parameters encoded with spaces being %20 and not +. Any good nice quick solutions of encoding the parameters correctly without using http_build_query?

like image 202
Svish Avatar asked Feb 13 '12 17:02

Svish


4 Answers

Since the URL is encoded when http_build_query returns, so that + are always and only spaces, you can just chain it with str_replace:

$query = str_replace('+', '%20', http_build_query($arr));

If you don't want to encode the ~ as well:

$query = str_replace(
    array('+', '%7E'), 
    array('%20', '~'), 
    http_build_query($arr)
);
like image 105
netcoder Avatar answered Nov 20 '22 00:11

netcoder


You can use de PHP_QUERY_RFC3986 flag.

$query = http_build_query($query_data, null, null, PHP_QUERY_RFC3986);
like image 36
Rodrigo Azevedo Avatar answered Nov 20 '22 00:11

Rodrigo Azevedo


You could also pass the query string through the rawurlencode function. Available in 5.3 it encodes to RFC 3986:

http://www.php.net/manual/en/function.rawurlencode.php

like image 45
Shane Avatar answered Nov 19 '22 23:11

Shane


Slightly more concise version of @cwd's answer.

public function httpBuildQuery3986(array $params, $sep = '&')
{
    $parts = array();
    foreach ($params as $key => $value) {
        $parts[] = sprintf('%s=%s', $key, rawurlencode($value));
    }

    return implode($sep, $parts);
}
like image 27
SpiffyJr Avatar answered Nov 19 '22 23:11

SpiffyJr