urlencode和urldecode,何时以及为何使用

时间:2018-03-09 07:52:48

标签: php urlencode

我心里有些疑惑:

  1. php中的urlencode和urldecode是什么?
  2. 每次使用查询字符串时我是否必须使用urlencode?
  3. 如果我先使用过urlencode,我是否必须使用urldecode?

    请解释一下这些事情。

1 个答案:

答案 0 :(得分:0)

编码和解码示例:

<?php

$items = [
    'artist' => 'Simon & Garfunkel',
    'song'   => 'Bridge over troubled water',
    'tags'   => 'harmony;vocal'
];

$query_string = http_build_query($items);
echo $query_string, "\n";

// alternatively build the query string

foreach(array_map('urlencode', $items) as $k => $v)
    $pairs[] = $k . '=' . $v;

$query_string = implode('&', $pairs);
echo $query_string, "\n";

// Going backwards
$url_encoded_pairs = explode('&', $query_string);
foreach($url_encoded_pairs as $pair) {
    list($key, $value) = explode('=', $pair);
    $params[$key] = urldecode($value);
}

var_export($params);

输出

artist=Simon+%26+Garfunkel&song=Bridge+over+troubled+water&tags=harmony%3Bvocal
artist=Simon+%26+Garfunkel&song=Bridge+over+troubled+water&tags=harmony%3Bvocal
array (
  'artist' => 'Simon & Garfunkel',
  'song' => 'Bridge over troubled water',
  'tags' => 'harmony;vocal',
)

superglobals $ _GET和$ _REQUEST已经被urldecoded。

另见: What's valid and what's not in a URI query?