欢迎访问 生活随笔!

ag凯发k8国际

当前位置: ag凯发k8国际 > 编程语言 > php >内容正文

php

php http build query -ag凯发k8国际

发布时间:2023/10/19 php 139 如意码农
ag凯发k8国际 收集整理的这篇文章主要介绍了 php http build query 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

(php 5, php 7)

http_build_query — 生成 url-encode 之后的请求字符串

说明¶

string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = php_query_rfc1738 ]]] )

使用给出的关联(或下标)数组生成一个经过 url-encode 的请求字符串。

参数¶

query_data

可以是数组或包含属性的对象。

一个 query_data 数组可以是简单的一维结构,也可以是由数组组成的数组(其依次可以包含其它数组)。

如果 query_data 是一个对象,只有 public 的属性会加入结果。

numeric_prefix

如果在基础数组中使用了数字下标同时给出了该参数,此参数值将会作为基础数组中的数字下标元素的前缀。

这是为了让 php 或其它 cgi 程序在稍后对数据进行解码时获取合法的变量名。

arg_separator

除非指定并使用了这个参数,否则会用 arg_separator.output 来分隔参数。

enc_type

默认使用 php_query_rfc1738

如果 enc_type 是 php_query_rfc1738,则编码将会以 » rfc 1738 标准和 application/x-www-form-urlencoded 媒体类型进行编码,空格会被编码成加号()。

如果 enc_type 是 php_query_rfc3986,将根据 » rfc 3986 编码,空格会被百分号编码()。

返回值¶

返回一个 url 编码后的字符串。

更新日志¶

版本 说明
5.4.0 加入了 enc_type 参数。
5.1.3 方括号也会被转义。
5.1.2 加入了参数 arg_separator

范例¶

example #1 http_build_query() 使用示例

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

echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&');

?>

以上例程会输出:

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

example #2 http_build_query() 使用数字下标的元素

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

echo http_build_query($data) . "\n";
echo http_build_query($data, 'myvar_');
?>

以上例程会输出:

0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext processor
myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext processor

example #3 http_build_query() 使用复杂的数组

$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_');
?>

这会输出:(为了可读性,字已经换行了)

user[name]=bob smith&user[age]=47&user[sex]=m&
user[dob]=5/12/1956&pastimes[0]=golf&pastimes[1]=opera&
pastimes[2]=poker&pastimes[3]=rap&children[bobby][age]=12&
children[bobby][sex]=m&children[sally][age]=8&
children[sally][sex]=f&flags_0=ceo

note:

只有基础数组中的数字下标元素“ceo”才获取了前缀,其它数字下标元素(如 pastimes 下的元素)则不需要为了合法的变量名而加上前缀。

example #4 http_build_query() 使用对象

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';
}

$parent = new parentclass();

echo http_build_query($parent);
?>

以上例程会输出:

pub=publicparent&pub_bar[pub]=publicchild

参见¶

  • parse_str() - 将字符串解析成多个变量
  • parse_ - 解析 url,返回其组成部分
  • urlencode() - 编码 url 字符串
  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理
 add a note

user contributed notes 19 notes

up
down
71

ilya rudenko¶

11 years ago
params with null value do not present in result string.

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

will produce:

test2=1

up
down
15

itsadok at gmail dot com¶

2 years ago
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, '&', php_query_rfc3986);

or possibly this:

http_build_query($query, null, ini_get('arg_separator.output'), php_query_rfc3986);

but not this:

// bad code!
    http_build_query($query, null, null, php_query_rfc3986);

up
down
21

anonymous¶

6 years ago
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.

to overcome this specify:

http_build_query($array, '', '&');

and not

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

up
down
29

eric dot muyser at gmail dot com¶

4 years ago
this function makes like this

files[0]=1&files[1]=2&...

to do it like this:

files[]=1&files[]=2&...

do this:

$query = http_build_query($query);
        $query = preg_replace('/[[0-9] ]/simu', '[]', $query);

up
down
9

vitaly dyatlov¶

4 years ago
correct implementation of coding the array of params without indexes (valdikks fixed code - didnt work for inner arrays):


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);
        }

up
down
12

anonymous¶

5 years ago
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);

will print
name=miller&age=23

up
down
6

irish [-@-] ytdj [-dot-] ca¶

7 years ago
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.

up
down
1

james at dimensionengineering dot com¶

2 years ago
be careful about example 1 -- it is exactly how *not* to implement things.

& as a separator is the url encoding.
& is html encoding.

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.

up
down
1

chat dot noir at arcor dot de¶

4 months ago
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();

foreach (explode($delimiter, $query) as $namevalue) {
    preg_match(
        '/^(?p[^=\[]*)(?p\[(?p[^\]]*(\]\[[^\]]*)*)\]?)?(?p=(?p.*))?$/', 
        $namevalue, 
        $namevalueparts
    );
    
    if (!empty($namevalueparts)) {
        $param =& $params[$namevalueparts['name']];
        
        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)) { $index  = (int) $index;  }
                    
                    if (!array_key_exists($index, $param)) {
                        $param[$index] = array();
                    }
                    $param =& $param[$index];
                }
            }
        }

if (!empty($namevalueparts['value_present'])) {
            $param = urldecode($namevalueparts['value']);
        } else {
            $param = '';
        }
    }
}

return $params;

}?>

up
down
0

rmaslo at archa dot cz¶

10 months ago
warning: different arrays may return the same result


$a1 = array('x[y]' => array('a'=>1));
$a2 = array('x' => array('y' => array('a'=>1)));
$q1 = http_build_query($a1);
$q2 = http_build_query($a2);
var_dump($a1);
echo '
';
var_dump($a2);
echo '
';
echo $q1;
echo '
';
echo $q2;
echo '
';

result:
array(1) { ["x[y]"]=> array(1) { ["a"]=> int(1) } }
array(1) { ["x"]=> array(1) { ["y"]=> array(1) { ["a"]=> int(1) } } }
x[y][a]=1
x[y][a]=1

up
down
0

mark simon¶

2 years ago
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:

$data=array(
        'a'=>'apple',
        'b'=>2,
        'c'=>null,
        'd'=>'…',
    );

//    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.

mark

up
down
0

netrox at aol dot com¶

8 years ago
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.

up
down
-1

joelhy¶

1 year ago
params with false value will be changed to zero in result string.

$arr = ['foo' => false];
echo http_build_query($arr);
?>

will produce:

foo=0

up
down
-1

joey dot qiang at innomative dot com¶

2 years ago
not recommending to eliminate the numeric indices like:
'arg[0]' --> 'arg[]'

the reason is this function will not include null values in the result string:

$data = array(
            'arg' => array(
                null,
                2,
                3
            )
        );
        echo http_build_query($data);

the output is something like "arg[1]=2&arg[2]=3";

up
down
-2

valdikss at gmail dot com¶

10 years ago
this function is wrong for http!
arrays in http is like this:

files[]=1&files[]=2&...

but function makes like this

files[0]=1&files[1]=2&...

here is normal function:

function cr_post($a,$b=\'\',$c=0){
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v){
if ($c) $k=$b.\"[]\"; elseif (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);}
?>

up
down
-2

v0idnull[try_to_spam_me_now] at gee-mail dot co¶

7 years ago
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.
up
down
-7

stocki dot r at gmail dot com¶

4 years ago
if you need only key value pairs, you can use this:

    $array = array(
        "type" => "welcome",
        "message" => "hello world!"
    );
    echo urldecode(http_build_query($array, '', ';'));
?>

result: type=welcome;message=hello world!

up
down
-7

kirils solovjovs¶

4 years ago
instead of some other suggestions that did not work for me, i found that the best way to build post content (e.g. for stream_context_create) is urldecode(http_build_query($query))
up
down
-34

jakub dot lopuszanski at nasza-klasa dot pl¶

4 years ago
while this is not documented, this http_build_query can return false on some inputs:
  //gives bool(false)
  var_dump(http_build_query('whatever'));
?>

总结

以上是ag凯发k8国际为你收集整理的php http build query的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得ag凯发k8国际网站内容还不错,欢迎将ag凯发k8国际推荐给好友。

  • 上一篇:
  • 下一篇:
网站地图