Php request url query

http_build_query

Generates a URL-encoded query string from the associative (or indexed) array provided.

Parameters

May be an array or object containing properties.

If data is an array, it may be a simple one-dimensional structure, or an array of arrays (which in turn may contain other arrays).

If data is an object, then only public properties will be incorporated into the result.

If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only.

This is meant to allow for legal variable names when the data is decoded by PHP or another CGI application later on.

The argument separator. If not set or null , arg_separator.output is used to separate arguments.

By default, PHP_QUERY_RFC1738 .

If encoding_type is PHP_QUERY_RFC1738 , then encoding is performed per » RFC 1738 and the application/x-www-form-urlencoded media type, which implies that spaces are encoded as plus ( + ) signs.

If encoding_type is PHP_QUERY_RFC3986 , then encoding is performed according to » RFC 3986, and spaces will be percent encoded ( %20 ).

Return Values

Returns a URL-encoded string.

Changelog

Examples

Example #1 Simple usage of http_build_query()

$data = array(
‘foo’ => ‘bar’ ,
‘baz’ => ‘boom’ ,
‘cow’ => ‘milk’ ,
‘null’ => null ,
‘php’ => ‘hypertext processor’
);

echo http_build_query ( $data ) . «\n» ;
echo http_build_query ( $data , » , ‘&’ );

The above example will output:

foo=bar&baz=boom&cow=milk&php=hypertext+processor foo=bar&baz=boom&cow=milk&php=hypertext+processor

Example #2 http_build_query() with numerically index elements.

$data = array( ‘foo’ , ‘bar’ , ‘baz’ , null , ‘boom’ , ‘cow’ => ‘milk’ , ‘php’ => ‘hypertext processor’ );

echo http_build_query ( $data ) . «\n» ;
echo http_build_query ( $data , ‘myvar_’ );
?>

The above example will output:

0=foo&1=bar&2=baz&4=boom&cow=milk&php=hypertext+processor myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_4=boom&cow=milk&php=hypertext+processor

Example #3 http_build_query() with complex arrays

$data = array(
‘user’ => array(
‘name’ => ‘Bob Smith’ ,
‘age’ => 47 ,
‘sex’ => ‘M’ ,
‘dob’ => ‘5/12/1956’
),
‘pastimes’ => array( ‘golf’ , ‘opera’ , ‘poker’ , ‘rap’ ),
‘children’ => array(
‘bobby’ => array( ‘age’ => 12 , ‘sex’ => ‘M’ ),
‘sally’ => array( ‘age’ => 8 , ‘sex’ => ‘F’ )
),
‘CEO’
);

echo http_build_query ( $data , ‘flags_’ );
?>

The above example will output: (word wrapped for readability)

user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M& user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera& pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12& children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8& children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO

Note:

Only the numerically indexed element in the base array «CEO» received a prefix. The other numeric indices, found under pastimes, do not require a string prefix to be legal variable names.

Example #4 Using http_build_query() with an object

class parentClass public $pub = ‘publicParent’ ;
protected $prot = ‘protectedParent’ ;
private $priv = ‘privateParent’ ;
public $pub_bar = null ;
protected $prot_bar = null ;
private $priv_bar = null ;

public function __construct () $this -> pub_bar = new childClass ();
$this -> prot_bar = new childClass ();
$this -> priv_bar = new childClass ();
>
>

class childClass public $pub = ‘publicChild’ ;
protected $prot = ‘protectedChild’ ;
private $priv = ‘privateChild’ ;
>

echo http_build_query ( $parent );
?>

The above example will output:

pub=publicParent&pub_bar%5Bpub%5D=publicChild

See Also

  • parse_str() — Parses the string into variables
  • parse_url() — Parse a URL and return its components
  • urlencode() — URL-encodes string
  • array_walk() — Apply a user supplied function to every member of an array

User Contributed Notes 24 notes

Params with null value do not present in result string.

$arr = array( ‘test’ => null , ‘test2’ => 1 );
echo http_build_query ( $arr );
?>

will produce:

Number to string conversion occured in is affected by locale settings, which might not be obvious.

setlocale ( LC_ALL , ‘us_En’ );
http_build_query ( $params ) // v=5.63

setlocale ( LC_ALL , ‘ru_RU’ );
http_build_query ( $params ) // v=5,63 mind the comma
?>

Passing null to $arg_separator is the same as passing an empty string, which is probably not what you want.

If you need to change the enc_type, use this:

http_build_query($query, null, ini_get(‘arg_separator.output’), PHP_QUERY_RFC3986);

// BAD CODE!
http_build_query($query, null, null, PHP_QUERY_RFC3986);

if you send boolean values it transform in integer :

$a = [teste1= true,teste2=false];
echo http_build_query($a)

//result will be teste1=1&teste2=0

This function makes like this

$query = http_build_query($query);
$query = preg_replace(‘/%5B1+%5D/simU’, ‘%5B%5D’, $query);

As noted before, with php5.3 the separator is & on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.

But if you post to a tomcat java server or something else the & might not be handled properly.

http_build_query($array); //gives & to some servers

If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following.

// mimic the behavior of $_GET, see also RFC 1738 and 3986.
$Delimiter = ini_get ( ‘arg_separator.input’ );
$Params = array();

if (!empty( $NameValueParts [ ‘indices_present’ ])) $Indices = explode ( ‘][‘ , $NameValueParts [ ‘indices’ ]);

foreach ( $Indices as $Index ) if (! is_array ( $Param )) $Param = array();
>

if ( $Index === » ) $Param [] = array();
end ( $Param );
$Param =& $Param [ key ( $Param )];
> else if ( ctype_digit ( $Index ))

if (! array_key_exists ( $Index , $Param )) $Param [ $Index ] = array();
>
$Param =& $Param [ $Index ];
>
>
>

if (!empty( $NameValueParts [ ‘value_present’ ])) $Param = urldecode ( $NameValueParts [ ‘value’ ]);
> else $Param = » ;
>
>
>

Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.

$post_data = array(‘name’=>’miller’, ‘address’=>array(‘address_lines’=>array()), ‘age’=>23);
echo http_build_query($post_data);

When using the http_build_query function to create a URL query from an array for use in something like curl_setopt($ch, CURLOPT_POSTFIELDS, $post_url), be careful about the url encoding.

In my case, I simply wanted to pass on the received $_POST data to a CURL’s POST data, which requires it to be in the URL format. If something like a space [ ] goes into the http_build_query, it comes out as a +. If you’re then sending this off for POST again, you won’t get the expected result. This is good for GET but not POST.

Instead you can make your own simple function if you simply want to pass along the data:

$post_url = » ;
foreach ( $_POST AS $key => $value )
$post_url .= $key . ‘=’ . $value . ‘&’ ;
$post_url = rtrim ( $post_url , ‘&’ );
?>

You can then use this to pass along POST data in CURL.

$ch = curl_init ( $some_url );
curl_setopt ( $ch , CURLOPT_POST , true );
curl_setopt ( $ch , CURLOPT_POSTFIELDS , $post_url );
curl_exec ( $ch );
?>

Note that at the final page that processes the POST data, you should be properly filtering/escaping it.

As noted, this function omits keys with null values. This could break some code which treats the key as boolean, and so has no value, or other code expecting the array to be populated regardless of value.

A workaround for this is to replace the null values with an empty string:

// Compensate for fact that http_build_query omits null values
foreach($data as &$datum) if($datum===null) $datum=»;

Losing the null-ness of the original is no real loss if it’s supposed to be a real query string. If the null is important, you could use a dummy value instead.

Be careful about Example 1 — it is exactly how *not* to implement things.

You should HTML encode your URL if embedding it in a web page. This is more involved than just replacing & with &. Doing as this example suggests is a security hole waiting to happen.

Correct implementation of coding the array of params without indexes (valdikks fixed code — didnt work for inner arrays):

I noticed that even with the magic quotes disabled, http_build_query() automagically adds slashes to strings.

So, I had to add «stripslashes» to every string variable.

on my install of PHP 5.3, http_build_query() seems to use & as the default separator. Kind of interesting when combined with stream_context_create() for a POST request, and getting $_POST[‘amp;fieldName’] on the receiving end.

When using http_build_query($args) where $args is an array; note that there is a limit to the size of array. See max_input_vars in your php.ini to increase this size.

Источник

Get Query String from URL in php

To get the query string from a URL in php, you can use $_GET super global to get specific key value pairs or $_SERVER super global to get the entire string.

// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_GET['key1']; echo $_GET['key2']; echo $_SERVER['QUERY_STRING']; //Output: value1 value2 key1=value1&key2=value2&key3=value3

A query string is a part of a URL that assigns values to specified parameters. When building web pages, query strings help us pass and access information to be used on our web pages.

When working in php, the ability to easily access and work with query strings is important.

To get a query string from a URL, there are a few different ways you can get the key value pairs.

To get a specific parameter from a query string, you can use $_GET super global to access individual parameters from the query string by name.

// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_GET['key1']; //Output: value1

If you want to get the entire query string, you can use the $_SERVER super global.

// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_SERVER['QUERY_STRING']; //Output: key1=value1&key2=value2&key3=value3

After getting the entire query string, you can parse it for the key value pairs with the php parse_str() function.

Using $_GET to Get Query String Parameters in php

The $_GET super global variable allows us to get individual key value pairs from query strings.

There are a few additional cases which occur when using query strings that I want to share with you.

First, in a query string, you can have duplicate key names followed by square brackets. This will create a child array in $_GET for that key with numerically indexed values.

// http://theprogrammingexpert.com/?key[]=value1&key[]=value2&key[]=value3 echo $_GET['key'][0]; echo $_GET['key'][1]; echo $_GET['key'][2]; //Output: value1 value2 value3

If the brackets are not empty, and have keys in them, then for a particular key, the child array belonging to the key will be an associative array.

// http://theprogrammingexpert.com/?key[ex1]=value1&key[ex2]=value2&key[ex3]=value3 echo $_GET['key']['ex1']; echo $_GET['key']['ex2']; echo $_GET['key']['ex3']; //Output: value1 value2 value3

Using $_SERVER to Get Query String in php

You can also use the $_SERVER super global variable to get the entire query string. After getting the query string, you can parse it with the php parse_str() function.

// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 query_string = $_SERVER['QUERY_STRING']; parse_str(query_string); echo $key1; echo $key2; echo $key3; //Output: value1 value2 value3

Hopefully this article has been useful for you to learn how to get query strings and work with them in php.

  • 1. php e – Using M_E and exp() Function to Get Euler’s Constant e
  • 2. php range() – Create Array of Elements Within Given Range
  • 3. php is_float() Function – Check if Variable is Float in php
  • 4. php array_key_exists() Function – Check if Key Exists in Array
  • 5. In PHP isset Method is Used For Checking if Variable is Defined
  • 6. php Square Root with sqrt Function
  • 7. php session_destroy() – Delete Session File Where Session Data is Stored
  • 8. php array_walk() – Modify Elements in Array with Callback Function
  • 9. Capitalize First Letter of String with php ucfirst() Function
  • 10. preg_replace php – Use Regex to Search and Replace

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Читайте также:  Содержание сайта
Оцените статью