Skip to content

Instantly share code, notes, and snippets.

@rondorkerin
Last active August 29, 2015 14:02
Show Gist options
  • Save rondorkerin/987dd14a6ebb85eb4f4f to your computer and use it in GitHub Desktop.
Save rondorkerin/987dd14a6ebb85eb4f4f to your computer and use it in GitHub Desktop.
Build a URL with a custom query string
public function testBuildURL()
{
$url = "http://website.com/mypage/?utm=campaign_1&foo=bar";
$wrongURL = $url . "?mykey=myvalue";
$parsedURL = parse_url($url);
// grab query string from URL
$queryString = $parsedURL['query'];
$parsedQueryString = array();
// parse query string into array
parse_str($queryString, $parsedQueryString);
// add your custom query params
$parsedQueryString['mykey'] = 'myvalue';
// build a query string out of the array
$newQuery = http_build_query($parsedQueryString);
$parsedURL['query'] = $newQuery;
// requires the PECL http extension
// $newURL = http_build_url("", $parsedURL);
// alternative url build:
$newURL = "http://website.com/mypage/?{$newQuery}";
echo $newURL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment