W3cubDocs

/Drupal 8

public static function Url::fromUserInput

public static Url::fromUserInput($user_input, $options = [])

Creates a Url object for a relative URI reference submitted by user input.

Use this method to create a URL for user-entered paths that may or may not correspond to a valid Drupal route.

Parameters

string $user_input: User input for a link or path. The first character must be one of the following characters:

  • '/': A path within the current site. This path might be to a Drupal route (e.g., '/admin'), to a file (e.g., '/README.txt'), or to something processed by a non-Drupal script (e.g., '/not/a/drupal/page'). If the path matches a Drupal route, then the URL generation will include Drupal's path processors (e.g., language-prefixing and aliasing). Otherwise, the URL generation will just append the passed-in path to Drupal's base path.
  • '?': A query string for the current page or resource.
  • '#': A fragment (jump-link) on the current page or resource.

This helps reduce ambiguity for user-entered links and paths, and supports user interfaces where users may normally use auto-completion to search for existing resources, but also may type one of these characters to link to (e.g.) a specific path on the site. (With regard to the URI specification, the user input is treated as a relative URI reference where the relative part is of type path-abempty.)

array $options: (optional) An array of options. See Url::fromUri() for details.

Return value

static A new Url object based on user input.

Throws

\InvalidArgumentException Thrown when the user input does not begin with one of the following characters: '/', '?', or '#'.

File

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

Class

Url
Defines an object that holds information about a URL.

Namespace

Drupal\Core

Code

public static function fromUserInput($user_input, $options = []) {
  // Ensuring one of these initial characters also enforces that what is
  // passed is a relative URI reference rather than an absolute URI,
  // because these are URI reserved characters that a scheme name may not
  // start with.
  if ((strpos($user_input, '/') !== 0) && (strpos($user_input, '#') !== 0) && (strpos($user_input, '?') !== 0)) {
    throw new \InvalidArgumentException("The user-entered string '$user_input' must begin with a '/', '?', or '#'.");
  }

  // fromUri() requires an absolute URI, so prepend the appropriate scheme
  // name.
  return static::fromUri('internal:' . $user_input, $options);
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Url.php/function/Url::fromUserInput/8.1.x