Reputation: 3416
If I have the url mysite.com/test.php?id=1
. The id
is set when the page loads and can be anything. There could also be others in there such as ?id=1&sort=new
. Is there a way just to add another to the end without finding out what the others are first then building a new url? thanks.
Upvotes: 4
Views: 24380
Reputation:
Use this function: https://github.com/patrykparcheta/misc/blob/master/addQueryArgs.php
function addQueryArgs(array $args, string $url)
{
if (filter_var($url, FILTER_VALIDATE_URL)) {
$urlParts = parse_url($url);
if (isset($urlParts['query'])) {
parse_str($urlParts['query'], $urlQueryArgs);
$urlParts['query'] = http_build_query(array_merge($urlQueryArgs, $args));
$newUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '?' . $urlParts['query'];
} else {
$newUrl = $url . '?' . http_build_query($args);
}
return $newUrl;
} else {
return $url;
}
}
$newUrl = addQueryArgs(array('add' => 'this', 'and' => 'this'), 'http://example.com/?have=others');
Upvotes: 1
Reputation: 163272
As an alternative to Kolink's answer, I think I would utilize http_build_query()
. This way, if there is nothing in the query string, you don't get an extra &
. Although, it won't really make a difference at all. Kolink's answer is perfectly fine. I'm posting this mainly to introduce you to http_build_query()
, as you will likely need it later:
http_build_query(array_merge($_GET, array('newvar'=>'123')))
Basically, we use http_build_query()
to take everything in $_GET
, and merge it with an array of any other parameters we want. In this example, I just create an array on the fly, using your example parameter. In practice, you'll likely have an array like this somewhere already.
Upvotes: 24
Reputation: 324610
"?".$_SERVER['QUERY_STRING']."&newvar=123";
Something like that.
Upvotes: 3