0

Assume this is my current URL:

http://example.com/search?param1=foo&param2=bar

Now I want to add param3=baz. So this is the code:

<a href="?param3=baz" >add param3</a>
//=> http://example.com/search?param3=baz

See? param1 and param2 will be removed. So I have to handle it like this:

<?php
    $query_str = parse_url($url, PHP_URL_QUERY);
    parse_str($query_str, $query_params);
    $query_params = $query_params == '' ? '?' : $query_params . '&';
?>

<a href="?{$query_params}param3=baz" >add param3</a>

Seems ugly, but ok, nevermind. Now what happens if a parameter be already exist and I need to edit it? Assume this example:

http://example.com/search?param1=foo&param2=bar

Now how can I make a link which edits the value of parame2? (plus keeping other parameters)

stack
  • 10,280
  • 19
  • 65
  • 117
  • how you come to know that this time i want to edit already existing and this time i want to add new-one?Means it's almost impossible to find-out the mood – Alive to die - Anant Jun 06 '17 at 09:59
  • @stack ..... http_build_query() use... for ref: https://stackoverflow.com/questions/5809774/manipulate-a-url-string-by-adding-get-parameters – RïshïKêsh Kümar Jun 06 '17 at 10:16

2 Answers2

0

There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.

You have to Do again:

search?param1=foo&param=bar&param3=baz

Or

Using Javascript is Possible

How to add a parameter to the URL?

Or

function currentUrl() {
    $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
    $host     = $_SERVER['HTTP_HOST'];
    $script   = $_SERVER['SCRIPT_NAME'];
    $params   = $_SERVER['QUERY_STRING'];

    return $protocol . '://' . $host . $script . '?' . $params;
}

Then add your value with something like;

echo currentUrl().'&param3=baz';

or

Whatever GET parameters you had will still be there and if param3 was a parameter before it will be overwritten, otherwise it will be included at the end.

http_build_query(array_merge($_GET, array("param3"=>"baz")))
RïshïKêsh Kümar
  • 4,734
  • 1
  • 24
  • 36
0

You can use function http_build_query to generate new query, like this:

$url = 'http://example.com/search?param1=foo&param2=bar';

$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $params);

$data = [
    'param3' => 'baz'
];

$params = array_merge($params, $data);

echo http_build_query($params) . "\n";

And output will be:

param1=foo&param2=bar&param3=baz

I use array_merge for override exist params, if we get url:

$url = 'http://example.com/search?param1=foo&param3=bar';

The same code output will be:

param1=foo&param3=baz

We override exist param and save old params.

TheMY3
  • 353
  • 3
  • 10