In PHP, is there an easy way to get part of a directory in a URI?

In PHP, is there an easy way to get only part of the HTTP URI directory? That is, given the URI with an optional file name and request, I only want a directory without a file or request name;

  Given returns
  ///
  /a.txt /
  /? x = 2 /
  /a.txt?x=2 /
  / foo / / foo /
  /foo/b.txt / foo /
  /foo/b.txt?y=3 / foo /
  / foo / bar / / foo / bar /
  /foo/bar/c.txt / foo / bar /

Etc.

I can not find the PHP function for this. I am using the following code snippet, but it is long and overly complex for something that seems to be one function;

$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_dir = substr($uri_path, 0, 1 + strrpos($uri_path, '/'));

Is there a cleaner way?

Edit

dirname () does not do what I want.

echo dirname("/foo/bar/");

Outputs;

/foo
+3
source
4

dirname .

, $uri_dir = dirname($_SERVER['REQUEST_URI']);

, pathinfo PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION PATHINFO_FILENAME. .

+7

, ,

$path=preg_replace('{/[^/]+$}','/', $uri);

dirname , , dirname ('/foo/bar/') '/foo' (, . Arvin, uri , !)

...

  • {} .
  • , :/
  • " " [^/]
    • ^ " " - , ,
    • :/
    • , /
  • + " 1 " - ,
  • $

, .

+1

dirname($uri_path); - . dirname()

strrpos() /, , , , dirname, dirname Windows \ /.

, parse_url() urldecoding .

-1
$dir = $_SERVER['PHP_SELF']; // $dir = '/foo/'; // also works
$dir = (substr($dir,-1)=='/') ? $dir : dirname($dir) . '/';

.

: 'http://' . $_SERVER['HTTP_HOST'] . $dir URI

The reason I will use PHP_SELF instead of REQUEST_URI is because in some other examples, if the user puts "/" in one of the arguments, you will get unexpected results without further cleaning. In addition, not all servers support all header variables, but those that are fairly common here.

-1
source

All Articles