PHP - parse current URL

Solution 1:

You can use parse_url();

$url = 'http://www.mydomain.com/abc/';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);

which would give you

Array
(
    [scheme] => http
    [host] => www.mydomain.com
    [path] => /abc/
)
/abc/

Update: to get current page url and then parse it:

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

print_r(parse_url(curPageURL()));

echo parse_url($url, PHP_URL_PATH);

source for curPageURL function

Solution 2:

Take a look at the parse_url() function. It'll break you URL into its component parts. The part you're concerned with is the path, so you can pass PHP_URL_PATH as the second argument. If you only want the first section of the path, you can then use explode() to break it up using / as a delimiter.

$url = "http://www.mydomain.com/abc/";
$path = parse_url($url, PHP_URL_PATH);
$pathComponents = explode("/", trim($path, "/")); // trim to prevent
                                                  // empty array elements
echo $pathComponents[0]; // prints 'abc'

Solution 3:

To retrieve the current URL, you can use something like $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

If you want to match exactly what is between the first and the second / of the path, try using directly $_SERVER['REQUEST_URI']:

<?php

function match_uri($str)
{
  preg_match('|^/([^/]+)|', $str, $matches);

  if (!isset($matches[1]))
    return false;

  return $matches[1];  
}

echo match_uri($_SERVER['REQUEST_URI']);

Just for fun, a version with strpos() + substr() instead of preg_match() which should be a few microseconds faster:

function match_uri($str)
{
  if ($str{0} != '/')
    return false;

  $second_slash_pos = strpos($str, '/', 1);

  if ($second_slash_pos !== false)
    return substr($str, 1, $second_slash_pos-1);
  else
    return substr($str, 1);
}

HTH

Solution 4:

<?php
$url = "http://www.mydomain.com/abc/"; //https://www... http://... https://...
echo substr(parse_url($url)['path'],1,-1); //return abc
?>