Last active
August 29, 2015 14:02
-
-
Save rondorkerin/987dd14a6ebb85eb4f4f to your computer and use it in GitHub Desktop.
Build a URL with a custom query string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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