Php parse url php url host

parse_url

This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.

This function is not meant to validate the given URL, it only breaks it up into the parts listed below. Partial and invalid URLs are also accepted, parse_url() tries its best to parse them correctly.

Parameters

Specify one of PHP_URL_SCHEME , PHP_URL_HOST , PHP_URL_PORT , PHP_URL_USER , PHP_URL_PASS , PHP_URL_PATH , PHP_URL_QUERY or PHP_URL_FRAGMENT to retrieve just a specific URL component as a string (except when PHP_URL_PORT is given, in which case the return value will be an int ).

Return Values

On seriously malformed URLs, parse_url() may return false .

If the component parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are:

  • scheme — e.g. http
  • host
  • port
  • user
  • pass
  • path
  • query — after the question mark ?
  • fragment — after the hashmark #

If the component parameter is specified, parse_url() returns a string (or an int , in the case of PHP_URL_PORT ) instead of an array . If the requested component doesn’t exist within the given URL, null will be returned. As of PHP 8.0.0, parse_url() distinguishes absent and empty queries and fragments:

http://example.com/foo → query = null, fragment = null http://example.com/foo? → query = "", fragment = null http://example.com/foo# → query = null, fragment = "" http://example.com/foo?# → query = "", fragment = ""

Previously all cases resulted in query and fragment being null .

Note that control characters (cf. ctype_cntrl() ) in the components are replaced with underscores ( _ ).

Changelog

Version Description
8.0.0 parse_url() will now distinguish absent and empty queries and fragments.

Examples

Example #1 A parse_url() example

var_dump ( parse_url ( $url ));
var_dump ( parse_url ( $url , PHP_URL_SCHEME ));
var_dump ( parse_url ( $url , PHP_URL_USER ));
var_dump ( parse_url ( $url , PHP_URL_PASS ));
var_dump ( parse_url ( $url , PHP_URL_HOST ));
var_dump ( parse_url ( $url , PHP_URL_PORT ));
var_dump ( parse_url ( $url , PHP_URL_PATH ));
var_dump ( parse_url ( $url , PHP_URL_QUERY ));
var_dump ( parse_url ( $url , PHP_URL_FRAGMENT ));
?>

Читайте также:  Javascript для базы данных

The above example will output:

array(8) < ["scheme"]=>string(4) "http" ["host"]=> string(8) "hostname" ["port"]=> int(9090) ["user"]=> string(8) "username" ["pass"]=> string(8) "password" ["path"]=> string(5) "/path" ["query"]=> string(9) "arg=value" ["fragment"]=> string(6) "anchor" > string(4) "http" string(8) "username" string(8) "password" string(8) "hostname" int(9090) string(5) "/path" string(9) "arg=value" string(6) "anchor"

Example #2 A parse_url() example with missing scheme

// Prior to 5.4.7 this would show the path as «//www.example.com/path»
var_dump ( parse_url ( $url ));
?>

The above example will output:

array(3) < ["host"]=>string(15) "www.example.com" ["path"]=> string(5) "/path" ["query"]=> string(17) "googleguy=googley" >

Notes

This function may not give correct results for relative or invalid URLs, and the results may not even match common behavior of HTTP clients. If URLs from untrusted input need to be parsed, extra validation is required, e.g. by using filter_var() with the FILTER_VALIDATE_URL filter.

Note:

This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP’s backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///. ) are allowed. For any other scheme this is invalid.

See Also

  • pathinfo() — Returns information about a file path
  • parse_str() — Parses the string into variables
  • http_build_query() — Generate URL-encoded query string
  • dirname() — Returns a parent directory’s path
  • basename() — Returns trailing name component of path
  • » RFC 3986

Источник

parse_url

Эта функция разбирает URL и возвращает ассоциативный массив, содержащий все компоненты URL, которые в нём присутствуют.

Эта функция не предназначена для проверки на корректность данного URL, она только разбивает его на нижеперечисленные части. Частичные URL также принимаются, parse_url() пытается сделать всё возможное, чтобы разобрать их корректно.

Список параметров

URL для разбора. Недопустимые символы будут заменены на знаки подчёркивания _.

Укажите одну из констант PHP_URL_SCHEME , PHP_URL_HOST , PHP_URL_PORT , PHP_URL_USER , PHP_URL_PASS , PHP_URL_PATH , PHP_URL_QUERY или PHP_URL_FRAGMENT , чтобы получить только конкретный компонент URL в виде строки ( string ). Исключением является указание PHP_URL_PORT , в этом случае возвращаемое значение будет типа integer .

Возвращаемые значения

При разборе значительно некорректных URL-адресов parse_url() может вернуть FALSE .

  • scheme — например, http
  • host
  • port
  • user
  • pass
  • path
  • query — после знака вопроса ?
  • fragment — после знака диеза #

Если параметр component определён, функция parse_url() вернёт строку ( string ) или число ( integer ), в случае PHP_URL_PORT ) вместо массива ( array ). Если запрошенный компонент не существует в данном URL, будет возвращён NULL .

Читайте также:  Java все методы treemap

Список изменений

Версия Описание
5.4.7 Исправлено распознавание host, если в URL отсутствовал компонент scheme и использовался ведущий разделитель компонентов.
5.3.3 Удалено E_WARNING , которое сообщало о невозможности разбора URL.
5.1.2 Добавлен параметр component .

Примеры

Пример #1 Пример использования parse_url()

echo parse_url ( $url , PHP_URL_PATH );
?>

Результат выполнения данного примера:

Array ( [scheme] => http [host] => hostname [user] => username [pass] => password [path] => /path [query] => arg=value [fragment] => anchor ) /path

Пример #2 Пример использования parse_url() при отсутствии протокола

// До 5.4.7 в path выводилось «//www.example.com/path»
var_dump ( parse_url ( $url ));
?>

Результат выполнения данного примера:

array(3) < ["host"]=>string(15) "www.example.com" ["path"]=> string(5) "/path" ["query"]=> string(17) "googleguy=googley" >

Примечания

Замечание:

Эта функция не работает с относительными URL.

Замечание:

Эта функция предназначена специально для разбора URL-адресов, а не URI. Однако, чтобы соответствовать требованиям обратной совместимости PHP, она делает исключение для протокола file://, в которой допускаются тройные слеши (file:///. ). Для любого другого протокола это недопустимо.

Смотрите также

  • pathinfo() — Возвращает информацию о пути к файлу
  • parse_str() — Разбирает строку в переменные
  • http_build_query() — Генерирует URL-кодированную строку запроса
  • http_build_url()
  • dirname() — Возвращает имя родительского каталога из указанного пути
  • basename() — Возвращает последний компонент имени из указанного пути
  • » RFC 3986

Источник

PHP parse_url и её обратная функция

parse_url($url, $component) – разбирает URL-адрес на компоненты, возвращая их в виде массива. При разборе некорректных URL, функция может вернуть false .

Разбор URL

Структура URL адреса

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); print_r($parse);

Результат:

Array ( [scheme] => https [host] => snipp.ru [path] => /php/parse-url [query] => page=1&sort=1 [fragment] => sample )
$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; echo parse_url($url, PHP_URL_SCHEME); // https echo parse_url($url, PHP_URL_HOST); // snipp.ru echo parse_url($url, PHP_URL_PORT); // NULL echo parse_url($url, PHP_URL_USER); // NULL echo parse_url($url, PHP_URL_PASS); // NULL echo parse_url($url, PHP_URL_PATH); // /php/parse-url echo parse_url($url, PHP_URL_QUERY); // page=1&sort=1 echo parse_url($url, PHP_URL_FRAGMENT); // sample

Кстати, GET-параметры будут представлены строкой вида page=1&sort=1 , преобразовать ее в массив можно с помощью функции parse_str() :

parse_str('page=1&sort=1', $query); print_r($query);

Результат:

echo http_build_query($query); // page=1&sort=1

Обратный parse_url

function reverse_parse_url(array $parts) < $url = ''; if (!empty($parts['scheme'])) < $url .= $parts['scheme'] . ':'; >if (!empty($parts['user']) || !empty($parts['host'])) < $url .= '//'; >if (!empty($parts['user'])) < $url .= $parts['user']; >if (!empty($parts['pass'])) < $url .= ':' . $parts['pass']; >if (!empty($parts['user'])) < $url .= '@'; >if (!empty($parts['host'])) < $url .= $parts['host']; >if (!empty($parts['port'])) < $url .= ':' . $parts['port']; >if (!empty($parts['path'])) < $url .= $parts['path']; >if (!empty($parts['query'])) < if (is_array($parts['query'])) < $url .= '?' . http_build_query($parts['query']); >else < $url .= '?' . $parts['query']; >> if (!empty($parts['fragment'])) < $url .= '#' . $parts['fragment']; >return $url; >

Удаление из URL GET-параметров:

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); unset($parse['query']); echo reverse_parse_url($parse); // https://snipp.ru/php/parse-url#sample

Замена домена:

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); $parse['host'] = 'example.com'; echo reverse_parse_url($parse); // https://example.com/php/parse-url?page=1&sort=1#sample

Источник

Читайте также:  Html input file по умолчанию

Parsing URL in PHP using parse_url()

Posted on Jul 29, 2022

To parse a URL with PHP, you need to use the built-in parse_url() function.

The parse_url() function takes a URL string and returns an associative array containing the URL’s components.

The syntax of the function is as follows:

  • The required $url string to parse
  • The $component integer tells the function to retrieve a specific URL component (optional)

Here’s an example of calling the parse_url() function:

    https  sebhastian.com  /php-parse-url  

The above code shows how parse_url() returns an associative array of three elements: the scheme , host , and path elements.

  • scheme
  • host
  • port
  • user
  • pass
  • path
  • query
  • fragment
  • PHP_URL_SCHEME
  • PHP_URL_HOST
  • PHP_URL_PORT
  • PHP_URL_USER
  • PHP_URL_PASS
  • PHP_URL_PATH
  • PHP_URL_QUERY
  • PHP_URL_FRAGMENT

Here’s an example of retrieving only the URL’s host:

The component you wish to retrieve will be returned as a string except for PHP_URL_PORT which will return an int .

When the component doesn’t exist, the function returns null .

For more information and examples, you can visit the parse_url documentation.

Now you’ve learned how to parse a URL using PHP. Good work! 👍

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Оцените статью