Do I need to get the current URL and know if after index.php has "?" or "&"

-3

The initial part to get the URL I already made using this code:

//URL ATUAL
$url_atual = str_replace("/", "", $_SERVER[REQUEST_URI]);
echo $url_atual;

..... If I'm on the url link returns me: index.php

If I'm on the url link returns me: index.php? module = tab

But I need to know how to know if after index.php is using any "?" like this example: index.php? module = tab .....

I need to create a link

if only index.php adds: ? lang = 1 ">

result index.php? lang = 1

or

if it is index.php? module = guide & lang = 1 ">

result index.php? module = guide & lang = 1

    
asked by anonymous 16.08.2018 / 01:04

3 answers

2

Would not it be simpler to use $_SERVER['QUERY_STRING'] that is made for exactly this?

If you want to add to existing links, it should look like this:

$querystring = $_SERVER['QUERY_STRING'];

//Adiciona o ? se a querystring não for vazia
if ($querystring != '') {
     $querystring = '?' . $querystring;
}

echo '<a href="index.php', $querystring,'">';
echo '<a href="index.php', $querystring,'&foo=bar">';

If you want to edit the query string values, just use the http_build_query() function with $_GET , assuming you have a URL like this:

 index.php?foo=bar&baz=2

And you want to change the value of baz= and generate the link then do this:

$querystring = '';

//Array vazias não passa no IF, não é necessário 'if (!empty())'
if ($_GET) {
    //Copia o GET
    $manipula = $_GET;

    $manipula['baz'] = 10; //Trocou o valor para 10

    $querystring = '?' . http_build_query($manipula, '', '&amp;'); // O uso de '&amp;' é para HTML, mas na URL ele será tratado como & apenas
}

echo '<a href="index.php', $querystring,'">';

This will generate a link like this:

index.php?foo=bar&baz=10
    
16.08.2018 / 02:06
0
  

Take the initial part with

$url_atual = str_replace("/", "", $_SERVER[REQUEST_URI]);
  

can bring unexpected results, see for example, if the url is

http://dominio.com/diretorio3/index.php?module=guia
  

$ _ SERVER [REQUEST_URI] will be

diretorio3/index.php?module=guia
  

and after the replace the result will be

diretorio3index.php?param=module=guia

Suggestion:

$url_atual = $_SERVER['REQUEST_URI'];

$result = (parse_url($url_atual , PHP_URL_QUERY));

if ($result !== null) {
    echo $url_atual."&lang=1";
} else {
    echo $url_atual."?lang=1";
}

parse_url - Interprets a URL and returns its components

PHP_URL_QUERY after querying ?

example in ideone

    
16.08.2018 / 01:31
-2

I made a code here that solved the problem

//URL ATUAL $url = str_replace("/", "", $_SERVER[REQUEST_URI]); if ($url == '') { $url_atual = "index.php"; } else { $url_atual = $url; }

echo $ url_atual; if ($ url_atual!="index.php") {echo "& lang = en"; } else {echo "? lang = en"; }

    
16.08.2018 / 01:18