- Получить части URL в PHP (parse_url, parse_str)
- Get Full URL & URL Parts In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- URL BASICS
- THE VARIOUS URL PARTS
- GET FULL URL & URL PARTS
- 1) URL PARTS IN PHP
- 2) GETTING THE FULL URL
- 3) COMMON URL PARTS
- PROTOCOL & HOST
- PATH ONLY
- FILENAME ONLY
- PATH WITH FILENAME
- EXTRA) PARSE URL
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- HOW ABOUT THE HASH?
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
- Get second segment from url
- PHP parse_url и её обратная функция
- Разбор URL
- Результат:
- Результат:
- Обратный parse_url
- Удаление из URL GET-параметров:
- Замена домена:
Получить части URL в PHP (parse_url, parse_str)
Существует несколько способов получения составных частей из URL в PHP скриптах. Но если требуется разбить URL на составляющие не из адреса текущей страницы, а из строковой переменной, то можно воспользоваться такими функциями как parse_url и parse_str. Первая разбивает URL на составные части, а вторая GET параметры на переменные
Предположим, что необходимо получить значение переменной «sort» из такой строки:
https://www.mousedc.ru/news/?show=all&sort=date
Первым делом разобьём эту строку на части, используя функцию «parse_url». Для этого напишем такой код:
$url = 'https://www.mousedc.ru/news/?show=all&sort=date'; $parts = parse_url( $url );
Array( [scheme] => https [host] => www.mousedc.ru [path] => /news/ [query] => show=all&sort=date )
Как видно из названий и значений ключей этого массива, в «query» попадают все GET параметры URL адреса. Остаётся только разбить их на составные части, чтобы достать значение параметра «sort». И легче всего сделать такое разбиение с помощью функции «parse_str». Она первым параметром принимает строку с параметрами (то есть наш $parts[‘query’] ), а во второй параметр записывает результат:
parse_str( $parts['query'] , $query ); echo $query['sort'];
В нашем случае функция «parse_str» получает в первый параметр строку show=all&sort=date и записывает в переменную $query следующий массив:
Array( [show] => all [sort] => date )
Остаётся лишь обратиться к определённому элементу по ключу. То есть искомое значение параметра «sort» будет содержаться в $query[‘sort’] .
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
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.
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.
EXTRA BITS & LINKS
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.
LINKS & REFERENCES
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
Search
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.
Get second segment from url
Use parse_url to get the path from the URL and then use explode to split it into its segments:
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $uri_segments = explode('/', $uri_path); echo $uri_segments[0]; // for www.example.com/user/account you will get 'user'
For some reason I had to change this to echo $uri_segment[1]; Otherwise, this is the perfect solution!
for mine, this works : $segments = explode(‘/’, trim(parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH), ‘/’)); echo $segments;
When working outside of WordPress [0] is the way to go but when working within I need to add [1] — interesting
$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/')); $numSegments = count($segments); $currentSegment = $segments[$numSegments - 1]; echo 'Current Segment: ' , $currentSegment;
Would result in Current Segment: second
You can change the numSegments -2 to get first
Here’s my long-winded way of grabbing the last segment, inspired by Gumbo’s answer:
// finds the last URL segment $urlArray = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $segments = explode('/', $urlArray); $numSegments = count($segments); $currentSegment = $segments[$numSegments - 1];
You could boil that down into two lines, if you like, but this way makes it pretty obvious what you’re up to, even without the comment.
Once you have the $currentSegment , you can echo it out or use it in an if/else or switch statement to do whatever you like based on the value of the final segment.
PHP parse_url и её обратная функция
parse_url($url, $component) – разбирает URL-адрес на компоненты, возвращая их в виде массива. При разборе некорректных URL, функция может вернуть false .
Разбор 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