Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http_build_query() without url encoding

Tags:

php

urlencode

Is there a way to use http_build_query() without having it URL encode according to some RFC standard?

Why I don't want to URL encode everything: I'm querying the Ebay API.. They honestly insist on parameter names not being URL encoded, as far as commas in parentheses. E.g. DomainName(0) is a parameter, and the query fails if those parens are encoded.

like image 805
bgcode Avatar asked May 26 '11 01:05

bgcode


People also ask

What is Http_build_query?

The http_build_query() function is an inbuilt function in PHP which is used to generate URL-encoded query string from the associative (or indexed) array.

What does Urlencoder encode do?

URL Encoding (Percent Encoding) URL encoding converts characters into a format that can be transmitted over the Internet. URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format.

What is Query String PHP?

A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters.


2 Answers

You can use urldecode() function on a result string which you get from http_build_query()

like image 80
UserJA Avatar answered Oct 13 '22 21:10

UserJA


PHP 5.3.1 (Buggy Behavior) http_build_query DOES escape the '&' ampersand character that joins the parameters. Example: user_id=1&setting_id=2.

PHP 5.4+ http_build_query DOES NOT escape the '&' ampersand character that joins the parameters. Example: user_id=1&setting_id=2

Example:

$params = array(
    'user_id' => '1', 
    'setting_id' => '2'
);
echo http_build_query($params);

// Output for PHP 5.3.1:
user_id=1&setting_id=2   // NOTICE THAT: '&' character is escaped

// Output for PHP 5.4.0+:
user_id=1&setting_id=2       // NOTICE THAT: '&' character is NOT escaped

Solution when targeting multiple version

Option #1: Write a wrapper function:

/** 
 * This will work consistently and will never escape the '&' character
 */
function buildQuery($params) {
    return http_build_query($params, '', '&');
}

Option #2: Ditch the http_build_query function and write your own.

like image 45
Basil Musa Avatar answered Oct 13 '22 19:10

Basil Musa