1

how can I get the current folder/directory name in PHP?

I have two pages on my site:

/about and /help

This is my code (in about and help page):

<?php

echo dirname("index.php");

?>

I want it to return: 'about' if I am on about page. And return 'help' if I am on help page. But it returns nothing.

If I am on this path: http://www.website.com/about/index.php I want it to just return about

TyhaiMahy
  • 85
  • 1
  • 2
  • 8

3 Answers3

4

getcwd();

or

dirname(__FILE__);

or (PHP5)

basename(__DIR__)

http://php.net/manual/en/function.getcwd.php

http://php.net/manual/en/function.dirname.php

Sevle
  • 3,109
  • 2
  • 19
  • 31
dp4solve
  • 411
  • 6
  • 18
0

echo dirname( __FILE__ );

Will print your file path

php-coder
  • 955
  • 1
  • 12
  • 23
0

If you want to get the directory where the current script resides, use dirname(__FILE__);

From your question I understand that you want to get it from the url instead. For that you can process the url (useful if URL Rewriting is done)

$full_url  = $_SERVER['REQUEST_URI'];
$url_array = explode("/", $full_url);
if(end($url_array)==='index.php' || end($url_array)==''){    
    $key = array_search('index.php', $url_array);
    if(!$key){
    //if index.php is not present and url ends with a '/'
        $key = count($url_array) - 1;
    }
    $target = (array_key_exists(($key-1), $url_array))?($key-1):$key;    
    $dir_name = $url_array[$target];
}else{
    $dir_name = end($url_array);
}
echo  $dir_name;
ash__939
  • 1,614
  • 2
  • 12
  • 21