Use the getcwd() Function to Get the Current Directory Name in PHP. The getcwd() function gives the current working directory. The returned value is a string on success.
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file. Consider the following directory structure −
The file_exists() function in PHP is an inbuilt function which is used to check whether a file or directory exists or not. The path of the file or directory you want to check is passed as a parameter to the file_exists() function which returns True on success and False on failure.
(PHP 4, PHP 5, PHP 7, PHP 8) getcwd — Gets the current working directory.
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.
To get only the name of the directory where script executed:
//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"
You can use dirname(__FILE__)
to get the path to the directory of the current file.
Example: /path_to/your_dir/your_file.php
:
// use dirname to get the directory of the current file
$path = dirname(__FILE__);
// $path here is now /path_to/your_dir
// split directory into array of pieces
$pieces = explode(DIRECTORY_SEPARATOR, $path);
// $pieces = ['path_to', 'your_dir']
// get the last piece
echo $pieces[count($pieces) - 1];
// result is: your_dir
echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only
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
$myVar = str_replace('/', '', $_SERVER[REQUEST_URI]);
libs/images/index.php
Result: images
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With