-1

I have a few doubts in my mind:

  1. What is urlencode and urldecode in php ?
  2. Should i have to use urlencode every time when using querystring ?
  3. Should i have to use urldecode if i have used urlencode first ?

Please explain me these things.

slavoo
  • 5,798
  • 64
  • 37
  • 39
Deepak Kumar
  • 129
  • 2
  • 13

1 Answers1

0

Example of encoding and decoding:

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

Output

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',
)

The superglobals $_GET and $_REQUEST are already urldecoded.

See also: What's valid and what's not in a URI query?

Progrock
  • 7,373
  • 1
  • 19
  • 25