8.5.x Url.php Url::fromUri($uri, $options = [])
8.0.x Url.php Url::fromUri($uri, $options = [])
8.1.x Url.php Url::fromUri($uri, $options = [])
8.2.x Url.php Url::fromUri($uri, $options = [])
8.3.x Url.php Url::fromUri($uri, $options = [])
8.4.x Url.php Url::fromUri($uri, $options = [])
8.6.x Url.php Url::fromUri($uri, $options = [])

Creates a new Url object from a URI.

This method is for generating URLs for URIs that:

  • do not have Drupal routes: both external URLs and unrouted local URIs like base:robots.txt
  • do have a Drupal route but have a custom scheme to simplify linking. Currently, there is only the entity: scheme (This allows URIs of the form entity:{entity_type}/{entity_id}. For example: entity:node/1 resolves to the entity.node.canonical route with a node parameter of 1.)

For URLs that have Drupal routes (that is, most pages generated by Drupal), use Url::fromRoute().

Parameters

string $uri: The URI of the resource including the scheme. For user input that may correspond to a Drupal route, use internal: for the scheme. For paths that are known not to be handled by the Drupal routing system (such as static files), use base: for the scheme to get a link relative to the Drupal base path (like the <base> HTML element). For a link to an entity you may use entity:{entity_type}/{entity_id} URIs. The internal: scheme should be avoided except when processing actual user input that may or may not correspond to a Drupal route. Normally use Url::fromRoute() for code linking to any any Drupal page.

array $options: (optional) An associative array of additional URL options, with the following elements:

  • 'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.
  • 'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.
  • 'absolute': Defaults to FALSE. Whether to force the output to be an absolute link (beginning with http:). Useful for links that will be displayed outside the site, such as in an RSS feed.
  • 'attributes': An associative array of HTML attributes that will be added to the anchor tag if you use the \Drupal\Core\Link class to make the link.
  • 'language': An optional language object used to look up the alias for the URL. If $options['language'] is omitted, it defaults to the current language for the language type LanguageInterface::TYPE_URL.
  • 'https': Whether this URL should point to a secure location. If not defined, the current scheme is used, so the user stays on HTTP or HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP.

Return value

\Drupal\Core\Url A new Url object with properties depending on the URI scheme. Call the access() method on this to do access checking.

Throws

\InvalidArgumentException Thrown when the passed in path has no scheme.

See also

\Drupal\Core\Url::fromRoute()

\Drupal\Core\Url::fromUserInput()

81 calls to Url::fromUri()
AggregatorTitleFormatter::viewElements in core/modules/aggregator/src/Plugin/Field/FieldFormatter/AggregatorTitleFormatter.php
Builds a renderable array for a field value.
BaseFieldFileFormatterBase::viewElements in core/modules/file/src/Plugin/Field/FieldFormatter/BaseFieldFileFormatterBase.php
Builds a renderable array for a field value.
BigPipeTest::testBigPipe in core/modules/big_pipe/src/Tests/BigPipeTest.php
Tests BigPipe-delivered HTML responses when JavaScript is enabled.
BigPipeTest::testBigPipeNoJs in core/modules/big_pipe/src/Tests/BigPipeTest.php
Tests BigPipe-delivered HTML responses when JavaScript is disabled.
ConfirmFormTest::testConfirmFormWithExternalDestination in core/modules/system/src/Tests/Form/ConfirmFormTest.php
Tests that the confirm form does not use external destinations.

... See full list

File

core/lib/Drupal/Core/Url.php, line 265

Class

Url
Defines an object that holds information about a URL.

Namespace

Drupal\Core

Code

public static function fromUri($uri, $options = []) {

  // parse_url() incorrectly parses base:number/... as hostname:port/...
  // and not the scheme. Prevent that by prefixing the path with a slash.
  if (preg_match('/^base:\\d/', $uri)) {
    $uri = str_replace('base:', 'base:/', $uri);
  }
  $uri_parts = parse_url($uri);
  if ($uri_parts === FALSE) {
    throw new \InvalidArgumentException("The URI '{$uri}' is malformed.");
  }

  // We support protocol-relative URLs.
  if (strpos($uri, '//') === 0) {
    $uri_parts['scheme'] = '';
  }
  elseif (empty($uri_parts['scheme'])) {
    throw new \InvalidArgumentException("The URI '{$uri}' is invalid. You must use a valid URI scheme.");
  }
  $uri_parts += [
    'path' => '',
  ];

  // Discard empty fragment in $options for consistency with parse_url().
  if (isset($options['fragment']) && strlen($options['fragment']) == 0) {
    unset($options['fragment']);
  }

  // Extract query parameters and fragment and merge them into $uri_options,
  // but preserve the original $options for the fallback case.
  $uri_options = $options;
  if (isset($uri_parts['fragment'])) {
    $uri_options += [
      'fragment' => $uri_parts['fragment'],
    ];
    unset($uri_parts['fragment']);
  }
  if (!empty($uri_parts['query'])) {
    $uri_query = [];
    parse_str($uri_parts['query'], $uri_query);
    $uri_options['query'] = isset($uri_options['query']) ? $uri_options['query'] + $uri_query : $uri_query;
    unset($uri_parts['query']);
  }
  if ($uri_parts['scheme'] === 'entity') {
    $url = static::fromEntityUri($uri_parts, $uri_options, $uri);
  }
  elseif ($uri_parts['scheme'] === 'internal') {
    $url = static::fromInternalUri($uri_parts, $uri_options);
  }
  elseif ($uri_parts['scheme'] === 'route') {
    $url = static::fromRouteUri($uri_parts, $uri_options, $uri);
  }
  else {
    $url = new static($uri, array(), $options);
    if ($uri_parts['scheme'] !== 'base') {
      $url->external = TRUE;
      $url
        ->setOption('external', TRUE);
    }
    $url
      ->setUnrouted();
  }
  return $url;
}

Comments

estoyausente’s picture

Internal example:

  $url = Url::fromUri('internal:/reports/search');

External example:

  $url = Url::fromUri('http://test.me/go/here');

Option example:

  $option = [
    'query' => ['user' => 'admin'],
  ];
  $url = Url::fromUri('internal:/reports/search', $option);
g3r4’s picture

Thank you very much for these examples !

ExTexan’s picture

+1 on the thank you. They were very helpful indeed.

maskedjellybean’s picture

I'm using Drupal 8.3.0 and both the Internal and External examples you provided result in this fatal PHP error:

"UnexpectedValueException: External URLs do not have internal route parameters. in Drupal\Core\Url->getRouteParameters()"

Has this code changed? I just need to generate a Url object from either a URL or URI. I have access to both and cannot find a way to generate a Url object. Thank you for any help.