Path from url php

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 .

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

Версия Описание
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
Читайте также:  Сочетание цветов hex html

Источник

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 ));
?>

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
Читайте также:  Void method return value java

Источник

Get Full URL & URL Parts In PHP (Simple Examples)

Welcome to a quick tutorial on how to get the full URL and URL parts in PHP. Need to get the path, base, domain, or query string from the URL? In Javascript, we can pretty much get all this information with just one line of code. But sadly in PHP, things are a little… backward.

  • To get the full URL in PHP – $full = (isset($_SERVER[«HTTPS»]) ? «https://» : «http://») . $_SERVER[«HTTP_HOST»] . $_SERVER[«REQUEST_URI»];
  • To remove the query string from the full URL – $full = strtok($full, «?»);

That should cover the basics, but if you need more specific “URL parts” – Read on for more examples!

TLDR – QUICK SLIDES

How To Get Full URL & URL Parts In PHP

TABLE OF CONTENTS

URL BASICS

All right, let us start with some “boring” basic URL parts. Yep, this stuff is important if you are new.

THE VARIOUS URL PARTS

  • Protocol – HTTP, HTTPS, FTP, WS, WSS, and whatever else.
  • Host – Better known as the “website address” to the non-technical folks.
  • Port – Usually left out. Commonly understood to be 80 for HTTP, 443 for HTTPS, and 21 for FTP.
  • Path – Beginners usually mistake this to be the “folder”, but it’s really not. I.E. The path can be virtual, not an actual physical folder.
  • File – Yes, the physical file name.
  • Query String – Extra information and parameters.

I know, it’s kind of ironic. The URL is supposed to be “easily understood” by humans, but there are so many parts to it.

GET FULL URL & URL PARTS

Now that you know the individual parts of a URL, let us now walk through how to obtain the full URL and the “common parts” using PHP.

1) URL PARTS IN PHP

2) GETTING THE FULL URL

 // (A4) THE PATH, FILE NAME, AND QUERY $url .= $_SERVER["REQUEST_URI"]; // (A5) INCLUDE QUERY STRING? if ($query===false) < $url = strtok($url, "?"); >// (A6) THE FULL URL return $url; > // (B) GET CURRENT URL echo getFullURL(true); // WITH QUERY echo getFullURL(); // WITHOUT QUERY

This is pretty much the “expanded version” of the introduction snippet, packaged into a function for your convenience.

Читайте также:  Stringbuffer to json java

3) COMMON URL PARTS

As for the “rest of the parts” that are not included in $_SERVER , we will need to do some mix-and-match on our own. Here are a few of the common ones.

PROTOCOL & HOST

// (A) PROTOCOL + DOMAIN $host = isset($_SERVER["HTTPS"]) ? "https://" : "http://" . $_SERVER["HTTP_HOST"] ; echo $host;

PATH ONLY

// (B) PATH ONLY $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); echo $path;

https://site.com/ path /file.php?p=123

FILENAME ONLY

// (C) FILENAME ONLY // USE BASENAME() TO GET THE FILE + STRIP QUERY STRING $file = basename($_SERVER["REQUEST_URI"], "?". $_SERVER["QUERY_STRING"]); echo $file;

https://site.com/path/ file.php ?p=123

PATH WITH FILENAME

// (D) PATH + FILENAME $filepath = strtok($_SERVER["REQUEST_URI"], "?"); echo $filepath;

https://site.com /path/file.php ?p=123

EXTRA) PARSE URL

For you guys who have a URL string from somewhere – You can use the parse_url() function to quickly get all the parts.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

HOW ABOUT THE HASH?

Want to get the hash section of the URL? For example, http://site.com/path/file.php #section . Sadly, it is nowhere to be found in $_SERVER . Your best bet is to use Javascript instead.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

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