I want to get the root directory folder name in php. I know its possible to get the root directory path using _DIR_ but i need the folder name. Do we have a php function that can do this? In case the solution is using regular expressions on directory path, is it compatible in all system environments? eg windows, mac, etc.. Basically i dont want to get C:\xampp\htdocs\myProject\ i want myProject.
Here is what i have tried $rootDirectoryPath= _DIR_; $rootDirectoryFoldername='';
2 Answers
try this,
$projectFolderName = explode('/', $_SERVER['PHP_SELF'])[1];
the $_SERVER['PHP_SELF'] returns path to current file relative to your root/public
folder of your server. You can then split the string on / which returns array of strings.
First element of that array is the name of your project folder.
When using on different operating systems, You can check presence of / or \ and determine delimiter to use to explode.
$delimiter = strpos($_SERVER['PHP_SELF'], '\\') ? '\\' : '/';
$projectFolderName = explode($delimiter, $_SERVER['PHP_SELF'])[1];
This is one way to do it.
4 Comments
Al-Amin
will it work for
C:\xampp\htdocs\myProject case ?Akash Sarode
in your case the directory separator is '\', so try explode function with '\'. You'll have to use '\\' as back slash is used to escape quotes.
Al-Amin
so your answer's code is not working in windows but the asker wants a solution for both case or any environment
Akash Sarode
I thought he wanted to get the name of project folder. Anyways, to make it work on different systems, there are number of ways you can try this, either check presence of \ or / and explode string depending on that, or if you are using some kind of environment variables file, then add a directory_separator variable there.
you can also use getcwd() with DIRECTORY_SEPARATOR
$folderName = substr(strrchr(getcwd(),DIRECTORY_SEPARATOR),1);
basename(getcwd())directory of the root pathbecause you can have really different architecture depending of how you built your application. you have to define it yourself. But if it's always as you define it you can probably doing it using__DIR__with an explode and get the last element with theDIRECTORY_SEPARATORas delimiter value to make it works on all file system.