PHP Get name of current directory


Translate

I have a php page inside a folder on my website.

I need to add the name of the current directory into a variable for example:

$myVar = current_directory_name;

Is this possible?


All Answers
  • Translate
    getcwd();
    

    or

    dirname(__FILE__);
    

    or (PHP5)

    basename(__DIR__) 
    

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

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

    You can use basename() to get the trailing part of the path :)

    In your case, I'd say you are most likely looking to use getcwd(), dirname(__FILE__) is more useful when you have a file that needs to include another library and is included in another library.

    Eg:

    main.php
    libs/common.php
    libs/images/editor.php
    

    In your common.php you need to use functions in editor.php, so you use

    common.php:

    require_once dirname(__FILE__) . '/images/editor.php';
    

    main.php:

    require_once libs/common.php
    

    That way when common.php is require'd in main.php, the call of require_once in common.php will correctly includes editor.php in images/editor.php instead of trying to look in current directory where main.php is run.


  • Translate

    To get only the name of the directory where script executed:

    //Path to script: /data/html/cars/index.php
    echo basename(dirname(__FILE__)); //"cars"
    

  • Translate

    For EXAMPLE

    Your Path = /home/serverID_name/www/your_route_Dir/

    THIS_is_the_DIR_I_Want

    A Soultion that WORKS:

    $url = dirname(\__FILE__);
    $array = explode('\\\',$url);
    $count = count($array);
    echo $array[$count-1];
    

  • Translate
    echo basename(__DIR__); will return the current directory name only
    echo basename(__FILE__); will return the current file name only
    

  • Translate

    Actually I found the best solution is the following:

    $cur_dir = explode('\\', getcwd());
    echo $cur_dir[count($cur_dir)-1];
    

    if your dir is www\var\path\ Current_Path

    then this returns Current_path


  • Translate

    $myVar = str_replace('/', '', $_SERVER[REQUEST_URI]);

    libs/images/index.php
    Result: images