Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

First decide where the content belongs: in the URL’s query string (such as ?page=2) or its path (such as /items/42). For a query parameter, add it to structured key/value data and generate the query with PHP’s http_build_query(); don’t insert text into the URL as an undifferentiated string. Preserve any existing query and fragment when rebuilding the URL.

Choose the URL component you need to change

A URL has distinct components, and “middle” can mean different things depending on the desired result:

  • Path: identifies a resource, for example /items/42.
  • Query: carries parameters after ?, for example ?page=2.
  • Fragment: points to a location within a resource after #, for example #details.

Use query-string construction for a parameter; use path-segment handling when the new content is part of the route. These components have different delimiters and encoding rules.

Add a query parameter without losing existing values

Keep query values as an array, add the new key, then generate the query string with http_build_query(). For a URL that may already contain a query or a fragment, parse its components and put the rebuilt query before the fragment:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
$url = 'https://example.com/search?term=php#results';
$newParameter = ['page' => 2];

$parts = parse_url($url);
$query = [];

if (isset($parts['query'])) {
    parse_str($parts['query'], $query);
}

$query = array_merge($query, $newParameter);
$parts['query'] = http_build_query($query);

$result = (isset($parts['scheme']) ? $parts['scheme'] . '://' : '')
    . ($parts['host'] ?? '')
    . (isset($parts['port']) ? ':' . $parts['port'] : '')
    . ($parts['path'] ?? '')
    . (isset($parts['query']) ? '?' . $parts['query'] : '')
    . (isset($parts['fragment']) ? '#' . $parts['fragment'] : '');

echo $result;
// https://example.com/search?term=php&page=2#results
?>

This example assumes a URL with a conventional scheme and host and demonstrates preserving its path, existing query values, and fragment. If the new key already exists, array_merge() replaces its value with the new one. Choose a different merge policy if you need to retain repeated keys or multiple values.

For a URL with no existing query, the simpler form is:

$url = 'https://example.com/items';
$params = ['page' => 2, 'sort' => 'recent'];
$result = $url . '?' . http_build_query($params);

PHP documents http_build_query() as the function for generating a URL-encoded query string. It handles separators and encoding of parameter values, so avoid manually concatenating ? and & around arbitrary input.

Encode according to the component

Query parameter values

For form-style query encoding, urlencode() encodes spaces as +. When the query needs RFC 3986 encoding, PHP’s http_build_query() supports PHP_QUERY_RFC3986, which represents spaces as %20:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);

Choose the convention expected by the system receiving the URL. Do not run an encoding function over the complete URL: characters such as /, ?, &, and # are structural delimiters.

Path segments

If the inserted content belongs in the path, encode the new segment rather than the entire path. Keep slash separators as separators:

$segment = rawurlencode($value);
$url = 'https://example.com/items/' . $segment;

This keeps characters within the value from being mistaken for path structure. Decide deliberately how to handle a value that represents multiple path segments; encoding the whole value as one segment is not the same as inserting several segments.

Parse and rebuild carefully

parse_url() splits a URL into components; it does not validate that the URL is valid or safe. PHP’s manual states: “This function is not meant to validate the given URL, it only breaks it up into the parts listed below.” Parser differences can matter for security—for example, if one parser is used to check a hostname allow-list and another is used to fetch the URL.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For newly written parsing code, the PHP manual recommends considering UriRfc3986Uri or UriWhatWgUrl unless compatibility with parse_url() behavior is required. The PHP URL parsing RFC, dated 2024-06-11 and marked implemented, describes the standard-aligned APIs. Select a parsing standard deliberately when URLs are untrusted or security-sensitive; parsing alone is not a substitute for validating the destination you intend to allow.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Parse query strings with an explicit result array

Pass parse_str() a destination array when reading an existing query. This makes the parsed values explicit and avoids creating variables in the current scope:

$query = [];
parse_str('term=php&page=2', $query);

// $query is ['term' => 'php', 'page' => '2']

Omitting the result argument was deprecated in PHP 7.2 and became disallowed in PHP 8.0. See the parse_str() manual.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.