I'm building multi-language support for PHP page. Let's say I have a page url:
http://mypage.php?user=eric&city=newyork
What is the common solution to switch between get parameters lang=en and lang=es while keeping the get parameters already in the url?
# Answer 1
A useful script that returns the relative URL of the current page with the current "GET data".
function getCurrentURL() {
$currentURL = basename($_SERVER["PHP_SELF"]);
$i = 0;
foreach($_GET as $key => $value) {
$i++;
if($i == 1) { $currentURL .= "?"; }
else { $currentURL .= "&"; }
$currentURL .= $key."=".$value;
}
return $currentURL;
}
?>
modify it and concatenate your language parameters accordingly
# Answer 2
You would not keep the GET Params in the url at all times, only when your setting the language, you would use sessions to remember what language that current client is using.
create the following function in your php
function getCurrentLanguage()
{
if(isset($_REQUEST['lang']))
{
//Validate that $_REQUEST['lang'] is valid
return $_SESSION['lang'] = $_REQUEST['lang'];
}
if(isset($_SESSION['lang']))
{
return $_SESSION['lang'];
}
return 'en'; //Default
}
now when the user comes to the site the default language would be English, but if he navigates to index.php?lang=es then the language would be set to es, so when he navigates around the site without the ?lang=es then it would show the Spanish version.
# Answer 3
It's better to use cookie or session/id data to store this kind of information.
I’ll have less things to carry around.
# Answer 4
If I understand the question correctly, you want a way to add a parameter to a URL or replace its value with a new value if it already exists.
Here's a function that does so safely in all manner of URLs:
function url_with_parameter($url, $name, $value) {
if(strpos($url, '?') === false) {
if (strpos($url, '#') === false) {
// No query and no fragment -- append a new query to the url
$newurl = $url.'?'.$name.'='.$value;
}
else {
// No query with fragment -- insert query before existing fragment
$newurl = str_replace('#', '?'.$name.'='.$value.'#', $url);
}
}
else {
if (strpos($url, $name.'=') === false) {
// With query, param does not exist -- insert at beginning of query
$newurl = str_replace('?', '?'.$name.'='.$value.'&', $url);
}
else {
// With query, param exists -- replace it
$parsed = parse_url($url, PHP_URL_QUERY);
parse_str($parsed, $vars);
$newurl = str_replace($name.'='.$vars[$name], $name.'='.$value, $url);
}
}
return $newurl;
}
Remember to call urlencode before using the output of this function to make a link.