Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active March 30, 2026 18:31
Show Gist options
  • Select an option

  • Save stemar/3411cc8ce8fc98bf19116223b851ef43 to your computer and use it in GitHub Desktop.

Select an option

Save stemar/3411cc8ce8fc98bf19116223b851ef43 to your computer and use it in GitHub Desktop.
Encode the query of a URL with RFC3986.
<?php
function encode_query(string $url): string {
if ($query = parse_url($url, PHP_URL_QUERY)) {
[$path] = explode($query, $url, 2);
parse_str($query, $data);
$query = http_build_query($data, "", NULL, PHP_QUERY_RFC3986);
if ($fragment = parse_url($url, PHP_URL_FRAGMENT)) {
$fragment = '#'.rawurlencode($fragment);
}
return join([$path, $query, $fragment]);
}
return $url;
}
@stemar
Copy link
Copy Markdown
Author

stemar commented Mar 27, 2026

// TEST
$url = 'http://username:password@hostname:9090/path?z=3,&arg[]=value d#anchor q';
echo encode_query($url);
http://username:password@hostname:9090/path?z=3%2C&arg%5B0%5D=value%20d#anchor%20q

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment