Adrian M.
Adrian M.

Reputation: 7443

PHP Get only directory path

I have:

$page_file_temp = $_SERVER["PHP_SELF"];

which will output: /templates/somename/index.php

I want to extract from that path only "/templates/somename/"

How can I do it? Thanks!

Upvotes: 16

Views: 67869

Answers (5)

NOTSermsak
NOTSermsak

Reputation: 356

Maybe this is your solution:

$rootPath = $_SERVER['DOCUMENT_ROOT'];
$thisPath = dirname($_SERVER['PHP_SELF']);
$onlyPath = str_replace($rootPath, '', $thisPath);

For example:

$_SERVER['DOCUMENT_ROOT'] is the server's root-path like this /home/abc/domains/abc.com/public_html

$_SERVER['PHP_SELF'] is about the whole path to that script like this /home/abc/domains/abc.com/public_html/uploads/home/process.php

Then we can have:

$rootPath like this /home/abc/domains/abc.com/public_html

$thisPath like this /home/abc/domains/abc.com/public_html/uploads/home

And $onlyPath like this /uploads/home

Upvotes: 10

Dominic Barnes
Dominic Barnes

Reputation: 28439

Using parse_url will account for GET variables and "fragments" (portion of URL after #) amongst other URL-specific parts.

$url = $_SERVER['PHP_SELF']; // OR $_SERVER['REQUEST_URI']

echo parse_url($url, PHP_URL_PATH);

Upvotes: 1

deadkarma
deadkarma

Reputation: 3144

An alternative:

$directory = pathinfo($page_file_temp,PATHINFO_DIRNAME);

http://www.php.net/manual/en/function.pathinfo.php

Upvotes: 0

David
David

Reputation: 7153

$page_directory = dirname($page_file_temp);

See dirname.

Upvotes: 34

Yacoby
Yacoby

Reputation: 55465

Take a look at the dirname() function.

From the documents, dirname() removes the trailing slash. If you want to keep it you can append the constant DIRECTORY_SEPARATOR to the result.

$dir = dirname('mystring/and/path.txt').DIRECTORY_SEPARATOR;

Upvotes: 2

Related Questions