Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bart's avatar
Level 13

Generate query URL

Hey everybody,

I'm searching for a method in PHP that generates a full query URL by passing a base URL (which could already include a query string) plus additional parameters.

I know that I could check if the URL contains a "?" and if so append with "&", otherwise append with "?". The question here is, if PHP has such a method on board?

I'll give you an example:

// Only works if $baseUrl not includes parameters
public function buildQuery($baseUrl, array $params) {
    return $baseUrl . '?' . http_build_query($params);
}

// But what if I do this?
$url = $this->buildQuery('https://my.endpoint.com/fetch?subject=php', ['maxlength' => 10]);

Any ideas?

Thanks a lot!!

0 likes
2 replies
bart's avatar
bart
OP
Best Answer
Level 13

Okay, I found a solution. Not a very clean one but for my personal taste better than an if check.

public function buildQuery($baseUrl, array $params) {
    parsedUrl = parse_url($baseUrl);
    parse_str(array_key_exists('query', $parsedUrl) ? $parsedUrl['query'] : '', $queryParams);
    $queryParams += $params;

    return sprintf('%s://%s%s?%s', $parsedUrl['scheme'], $parsedUrl['host'], $parsedUrl['path'], http_build_query($queryParams));
}
Corsari's avatar

Hello Bart, I hope so much you can still get notifications for this post :-)

Since looks like you had the situation for use them ...

.. may I kindly ask you to gently give some rough ideas about when and why they would become useful

  • http_build_query
  • parse_url
  • parse_str

?

thank you if you will teach/talk about the scenario

Robert

Please or to participate in this conversation.