Calling Url::fromUri() with an uri having a query part and passing an additional query in the option parameter results in an invalid url

Created on 12 July 2023, 12 months ago
Updated 14 July 2023, 12 months ago

Problem/Motivation

When you call Url::fromUri() with an uri, which already has the query part, and pass an additional query in the second parameter, then the result will be an invalid url.

Steps to reproduce

Here is an example code to reproduce the issue:

// Url with query
$url = 'https://hostname/path/?foo=1&bar=2';

// Pass url and additional query parameter
$url = \Drupal\Core\Url::fromUri(
  $url,
  ['query' => ['baz' => 3]]
)->toUriString();

// Output: https://hostname/path/?foo=1&bar=2?baz=3
echo $url . PHP_EOL;

The result is an invalid url, which has two question marks.

Proposed resolution

Following line within the else condition at the bottom of the fromUri() function should not use the passed $uri parameter, it should use a cleaned version of it, where the query part is removed.

$url = new static($uri, [], $options);

This version would fix it:

$url = new static(trim(strtok($uri, '?')), [], $options);

Remaining tasks

User interface changes

API changes

Data model changes

Release notes snippet

🐛 Bug report
Status

Needs work

Version

11.0 🔥

Component
Base 

Last updated 33 minutes ago

Created by

🇩🇪Germany m.purc

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024