1

Hello guys im sorry but i am newbie to php, in my site i have multiple language with GET.. Example site.com/index.php?lang=en to the nav menu i have a code like this

<?php
    $url = $_SERVER[REQUEST_URI];
    $query = parse_url($url, PHP_URL_QUERY);
    // Returns a string if the URL has parameters or NULL if not
    if ($query) {
        $url .= '&lang=';
    } else {
        $url .= '?lang=';
    }
?> 
<li><a href="<?php echo $url;?>en">

My problem is when the lang is set. Example site.com/index.php?lang=en when the user change the lang adds the lang to site.com/index.php?lang=en&lang=gr .

I want to "replace" the lang and not have a url like site.com/index.php?lang=gr&lang=en&lang=en&lang=en&lang=en

thank you guys

2
  • 3
    Why dont you just use $_GET it would be simpler and you woudl not cause the multipe parameter issue Commented Mar 7, 2017 at 14:40
  • I use $_GET. But in the future i want to have multiple $_GETs Commented Mar 7, 2017 at 14:55

3 Answers 3

1

try this, it's manage all type of query string you can receive

<?php

$url = $_SERVER[REQUEST_URI];
$url_without_query_string = strtok($url, '?');
$query = array();
parse_str(parse_url($url, PHP_URL_QUERY), $query);
$query['lang'] = 'en';

$new_url = $url_without_query_string . '?' . http_build_query($query);
?>
<li><a href="<?php echo $new_url; ?>">
Sign up to request clarification or add additional context in comments.

Comments

0

If when you have a querystring passed, you check if lang is part of that string using $_GET['lang'] then you can decide correctly if you want to add a new default one or use the existing one.

<?php
    $default_lang = 'en'

    $url = $_SERVER[REQUEST_URI];
    $query = parse_url($url, PHP_URL_QUERY);
    // Returns a string if the URL has parameters or NULL if not
    if ($query) {
        // we have a querystring
        // does it contain a lang already or not
        $url .= isset($_GET['lang'] ? '' : "&lang=$default_lang";
    } else {
        // nothing in the querystring so force a lang
        $url .= "?lang=$default_lang";
    }
?> 
<li><a href="<?php echo $url;?>">

2 Comments

It's good idea, but i have 2 languages, or 3-4-5, how to add the "gr, en, ro .. etc" to the links???
Surely that is up to the user to click something which adds the correct lang=?? to the url when they click a selection. My code just keeps the one selected, and if nothing is selected uses en as a default
0

I think is better to usea session variable. If an user change the language, you only overwrite de value of the session var.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.