Windows directory path in php

PHP Get name of current directory

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; 

9 Answers 9

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.

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

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

require_once dirname(__FILE__) . '/images/editor.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.

Note that if you use an include or a required, __DIR__ is the path of the included file and NOT the current directory

This is a bit misleading. __DIR__ is basically equivalent to dirname(__FILE__) (stackoverflow.com/a/2749423/446106). basename(__DIR__) is not.

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.

// 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 

The OP seems to have already accepted an answer to their problem. Although you’ve clearly added value, do you need to vent your furstrations here?

stackoverflow.com/help/formatting will explain how to make things bold avoiding the use of caps, which you have quite rightly pointed out denotes shouting on the internet.

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

Watch out, in Linux servers we do not use backslash but the slash. PHP has a magic constant to make it cross platform, see PATH_SEPARATOR

$myVar = str_replace(‘/’, », $_SERVER[REQUEST_URI]);

libs/images/index.php
Result: images

To get the names of current directory we can use getcwd() or dirname(__FILE__) but getcwd() and dirname(__FILE__) are not synonymous. They do exactly what their names are. If your code is running by referring a class in another file which exists in some other directory then these both methods will return different results.

For example if I am calling a class, from where these two functions are invoked and the class exists in some /controller/goodclass.php from /index.php then getcwd() will return ‘/ and dirname(__FILE__) will return /controller .

I use this line to get the actual file directory name without the path. (For windows)

substr(dirname(__FILE__), strrpos(dirname(__FILE__), '\\') + 1) 

I changed it a bit to work on Linux also

substr(dirname(__FILE__), strrpos(str_replace('\\', '/', dirname(__FILE__)), '/') + 1) 

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A library to get Microsoft Windows directory paths in PHP.

License

gibbs/php-windows-base-dir

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

PHP Windows Base Directory

A library to return various Microsoft Windows directory/folder paths based on runtime environment variables.

Install via composer with;

composer require gibbs/php-windows-base-dir
$wbd = new WindowsBaseDir\Wbd; // Print various paths echo $wbd->getCommonProgramFilesPath(); echo $wbd->getCommonProgramFilesX86Path(); echo $wbd->getHomeDrivePath(); echo $wbd->getProgramDataPath(); echo $wbd->getProgramFilesPath(); echo $wbd->getSystemDrivePath(); echo $wbd->getSystemRootPath(); echo $wbd->getTempPath(); if ($wbd->isWindowsEnvironment()) < $home = $wbd->getHomeDrivePath() . $wbd->getHomePath(); > else < // . >
$paths = (new WindowsBaseDir\Wbd)->getAllEnvironmentPaths();
Array ( [ALLUSERSPROFILE] => C:\ProgramData [APPDATA] => C:\Users\JoeBloggs\AppData\Roaming [COMSPEC] => C:\WINDOWS\system32\cmd.exe [COMMONPROGRAMFILES] => C:\Program Files (x86)\Common Files [COMMONPROGRAMFILES(X86)] => C:\Program Files (x86)\Common Files [DRIVERDATA] => C:\Windows\System32\Drivers\DriverData [HOMEDRIVE] => C: [HOME] => \Users\JoeBloggs [LOCALAPPDATA] => C:\Users\JoeBloggs\AppData\Local [LOGONSERVER] => \\DESKTOP-QI5UIAH [ONEDRIVE] => C:\Users\JoeBloggs\OneDrive [PATH] => C:\Python27\;C:\Python27\Scripts;C:\Windows\system32 [PROGRAMDATA] => C:\ProgramData [PROGRAMFILES] => C:\Program Files (x86) [PROGRAMFILES(X86)] => C:\Program Files (x86) [PUBLIC] => C:\Users\Public [SYSTEMDRIVE] => C: [SYSTEMROOT] => C:\WINDOWS [TEMP] => C:\Users\JoeBloggs\AppData\Local\Temp [USERPROFILE] => C:\Users\JoeBloggs [WINDIR] => C:\WINDOWS )

Alternatively use getAllPaths for underscore separated and lowercase keys:

$paths = (new WindowsBaseDir\Wbd)->getAllPaths();
Array ( [all_users_profile] => C:\ProgramData [app_data] => C:\Users\JoeBloggs\AppData\Roaming [com_spec] => C:\WINDOWS\system32\cmd.exe [common_program_files] => C:\Program Files (x86)\Common Files [common_program_files_x86] => C:\Program Files (x86)\Common Files [driver_data] => C:\Windows\System32\Drivers\DriverData [home_drive] => C: [home] => \Users\JoeBloggs [local_app_data] => C:\Users\JoeBloggs\AppData\Local [logon_server] => \\DESKTOP-QI5UIAH [one_drive] => C:\Users\JoeBloggs\OneDrive [path] => C:\Python27\;C:\Python27\Scripts;C:\Windows\system32 [program_data] => C:\ProgramData [program_files] => C:\Program Files (x86) [program_files_x86] => C:\Program Files (x86) [public] => C:\Users\Public [system_drive] => C: [system_root] => C:\WINDOWS [temp] => C:\Users\JoeBloggs\AppData\Local\Temp [user_profile] => C:\Users\JoeBloggs [win_dir] => C:\WINDOWS )

Copy phpunit.dist.xml to phpunit.xml and run

Источник

Get Root Directory Path of a PHP project

How can I get the path to RootDirectory of the system ( MySystem ), without hardcoding the Folder Name?

13 Answers 13

For PHP >= 5.3.0 try

And make your path relative.

this is just awesome, I tried $_SERVER[‘DOCUMENT_ROOT’], dirname(), $_SERVER[‘SCRIPT_NAME’] etc. but this worked excellently!

It does depends where you use __DIR__ . It is relative to the file itself, so if in an include, inside a sub directory, it’ll not return just your root directory.

quick note for anyone that stumbles across this answer looking for the answer of the asked question, DIR gets the directory of the current file not the project root unless you call it in a file that is in the project root, but as php doesn’t have the concept of a project all paths have to be absolute or relative to the current location

Please do not upvote an answer that does not address correctly the question, just because it helped you.

Then D: is what you are looking for, isn’t it? In that case you could explode the string by slashes and return the first one:

$pathInPieces = explode('/', $_SERVER['DOCUMENT_ROOT']); echo $pathInPieces[0]; 

This will output the server’s root directory.

Update: When you use the constant DIRECTORY_SEPARATOR instead of the hardcoded slash ( ‘/’ ) this code is also working under Windows.

Update 2: The $_SERVER global variable is not always available. On command line (cli) for example. So you should use __DIR__ instead of $_SERVER[‘DOCUMENT_ROOT’] . __DIR__ returns the path of the php file itself.

if your root directory path is in the form of /var/public/www» then using this method the first string in the array will be empty (0)/(1)/(2)/(3). the root will be the second string $pathInPieces[1]

Gets the current working directory.

I want to point to the way WordPress handles this:

define( 'ABSPATH', dirname( __FILE__ ) . '/' ); 

As WordPress is very heavy used all over the web and also works fine locally I have much trust in this method. You can find this definition on the bottom of your wordpress wp-config.php file

I guess this only works when you have two levels of directories. Right? I mean, when call it from base_project_directory/folder1/folder2/folder3/file.php it doesn’t return the base_project_directory.

«As WordPress is very heavy used all over the web and also works fine locally I have much trust in this method.» I don’t believe this is a particularly good argument given the WP code quality and security track record.

@AlexBarker I would contest the fact your implying that WP has a bad security track record. It’s actually pretty secure and has a respinsive team focused on secuity — core has had very few exploited security issues in recent years (including as far back as when you commented).

actually this doesn’t work. Didn’t investigate too much, but it looks like the double dirname actually strips a directory out (probably not what people who come to this thread want -> i.e. me)

@43matthew You’re right. Past then it worked this way but obviously not anymore. As WP also changed the definition I updated my answer accordingly. Thanks for pointing this out.

At this moment, PHP itself does not provide a way to get the project’s root directory for sure.

But you can implement a very simple method yourself that will do exactly what you’re looking for.

Create a new file in your project, let say D:/workspace/MySystem/Code/FilesManager.php (use whatever name and path suit you the best). Then, use the following code:

Now you can do this in, let’s say D:/workspace/MySystem/Code/a/b/c/Feature.php :

echo FilesManager::rootDirectory(); 

And the expected result should be:

The output will be the same no matter where your «feature» file is located in the project.

Explanation

dirname is used to return the parent directory of the first parameter. We use the magic constant __FILE__ to give it FilesManager.php ‘s path. The second parameter tells how many times to go up in the hierarchy. In this case, we need to do it twice, but it really depends where you put your file in the hierarchy. You can omit the second parameter if you only need to got up once, meaning the file is located in the root. But then, you can return __DIR__ directly instead.

This solution is guaranteed to work, no matter where the root is located on your server. Unless you end up moving the utility class somewhere else in the hierarchy.

Additional note

I’d avoid using DOCUMENT_ROOT for the following reasons (according to this answer):

  • It makes your application dependent on the server.
  • The Apache setup may give an incorrect path to the root directory.

Источник

Читайте также:  Установка java jre windows
Оцените статью