I have a few doubts in my mind:
- What is urlencode and urldecode in php ?
- Should i have to use urlencode every time when using querystring ?
- Should i have to use urldecode if i have used urlencode first ?
Please explain me these things.
I have a few doubts in my mind:
Please explain me these things.
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.