I've done quite a bit of searching for this, so I'm sorry if this is a dupe.
Anyway, I need to get the name of the folder the current file is in. For example, I want to convert something like example.com/folder/subfolder/file.php
to subfolder
.
My current code is dirname($_SERVER['PHP_SELF'])
, but that returns /folder/subfolder
instead of subfolder
. Thank you!
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.
If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.
__DIR__ : The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__) . This directory name does not have a trailing slash unless it is the root directory.
The simpliest way is:
basename(__DIR__);
https://www.php.net/manual/en/language.constants.magic.php
You need to combine your existing code using dirname()
with a call to basename()
:
$parent = basename(dirname($_SERVER['PHP_SELF']));
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