PHP Doku:: Ermittelt das aktuelle Arbeitsverzeichnis - function.getcwd.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzDateisystemrelevante ErweiterungenVerzeichnis-FunktionenVerzeichnis-Funktionengetcwd

Ein Service von Reinhard Neidl - Webprogrammierung.





(PHP 4, PHP 5)

getcwdErmittelt das aktuelle Arbeitsverzeichnis


string getcwd ( void )

Gibt das aktuelle Arbeitsverzeichnis zurück.


Gibt bei Erfolg das aktuelle Arbeitsverzeichnis zurück, im Fehlerfall FALSE.

Auf einigen Unix-Varianten gibt getcwd() FALSE zurück, wenn eines der darüber liegenden Verzeichnisse keine Lese- oder Suchrechte haben, auch wenn das aktuelle Verzeichnis diese hat. Lesen Sie chmod() für weitergehende Informationen über Modi und Zugriffsrechte.


Beispiel #1 getcwd() Beispiel


// aktuelles Verzeichnis
echo getcwd() . "\n";


// aktuelles Verzeichnis
echo getcwd() . "\n";


Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:


Siehe auch

  • chdir() - Wechseln des Verzeichnisses
  • chmod() - Ändert die Zugriffsrechte einer Datei

19 BenutzerBeiträge:
- Beiträge aktualisieren...
14.07.2010 13:04
As you could read in
the CLI SAPI does - contrary to other SAPIs - NOT automatically change the current working directory to the one the started script resides in.

A very simple workaround to regain the behaviour you're used to from your "ordinary" webpage scripting is to include something like that at the beginning of your script:

( dirname ( __FILE__ ) );

But because this is about reading or "finding" pathes, you might appreciate it if I share some more sophisticated tricks I frequently use in CLI scripts ...

// Note: all pathes stored in subsequent Variables end up with a DIRECTORY_SEPARATOR

// how to store the working directory "from where" the script was called:
$initial_cwd = preg_replace( '~(\w)$~' , '$1' . DIRECTORY_SEPARATOR , realpath( getcwd() ) );

// how to switch symlink-free to the folder the current file resides in:
chdir( dirname ( realpath ( __FILE__ ) ) );

// how to store the former folder in a variable:
$my_folder = dirname( realpath( __FILE__ ) ) . DIRECTORY_SEPARATOR;

// how to get a path one folder up if $my_folder ends with \class\ or /class/ :
$my_parent_folder = preg_replace( '~[/\\\\]class[/\\\\]$~' , DIRECTORY_SEPARATOR , $my_folder );

// how to get a path one folder up in any case :
$my_parent_folder = preg_replace( '~[/\\\\][^/\\\\]*[/\\\\]$~' , DIRECTORY_SEPARATOR , $my_folder );

// how to make an array of OS-style-pathes from an array of unix-style-pathes
// (handy if you use config-files or so):
foreach( $unix_style_pathes as $unix_style_path )
$os_independent_path[] = str_replace( '/' , DIRECTORY_SEPARATOR , $unix_style_path );

bvidinli at gmail dot com
21.01.2009 10:13
if you link your php to /bin/linkedphp  and your php is at for ex /home/actual.php

when you run linkedphp in somewhere in your filesystem,
getcwd returns /bin instead of working dir,

solution: use dirname(__FILENAME__) instead
ash at ashmckenzie dot org
19.11.2008 2:37
It appears there is a change in functionality in PHP5 from PHP4 when using the CLI tool.  Here is the example: -

cd /tmp

cat > foo.php << END
print getcwd() . "\n";

cd /

php -q /tmp/foo.php

PHP4 returns /tmp
PHP5 returns /

Something to be aware of.
Wolfgang M. Pauli
5.05.2008 4:44
If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link (similarly when parent etc. is symbolic link). There might be a better solution, but this worked for me (linux):
<? php
= exec('pwd');
znupi69NOSPAMHERE at gmail dot com
3.03.2008 19:39
In response to myself: that function will not work for cases like:
/usr/bin$: /home/johndoe/Work/script.php
So here's a better and simpler way (I think this one works for all cases)
function get_file_dir() {
Knock yourself out :)
znupi69NOSPAMHERE at gmail dot com
2.03.2008 16:01
When running PHP on the command line, if you want to include another file which is in the same directory as the main script, doing just
include './otherfile.php';
might not work, if you run your script like this:
/$ /path/to/script.php
because the current working dir will be set to '/', and the file '/otherfile.php' does not exist, because it is in '/path/to/otherfile.php'.
So, to get the directory in which the script resides, you can use this function:
function get_file_dir() {
$dir = dirname(getcwd() . '/' . $argv[0]);
$curDir = getcwd();
$dir = getcwd();
So you can use it like this:
include get_file_dir() . '/otherfile.php';
// or even..
Spent some time thinking this one out, maybe it helps someone :)
leonbrussels at gmail dot com
17.12.2007 17:10
This is a function to convert a path which looks something like this:


To a proper directory path:


function simplify_path($path) {

//saves our current working directory to a variable
$oldcwd = getcwd();
//changes the directory to the one to convert
//$path is the directory to convert (clean up), handed over to the //function as a string

gstr_replace('\\', '/', getcwd());

//change the cwd back to the old value to not interfere with the script


This function is really useful if you want to compare two filepaths which are not necesarily in a "cleaned up" state. It works in *NIX and WINDOWS alike

ab5602 at wayne dot edu
30.09.2007 19:33
If getcwd() returns nothing for you under Solaris with an NFS mounted subdirectory, you are running into an OS bug that is supposedly fixed in recent versions of Solaris 10.  This same OS bug effects the include() and require() functions as well.
troy dot cregger at gmail dot com
26.01.2007 21:10
Take care if you use getcwd() in file that you'll need to include (using include, require, or *_once) in a script located outside of the same directory tree.

//in /var/www/main_document_root/include/
if (strpos(getcwd(),'main_')>0) {
//code to set up main DB connection

//in home/cron_user/maintenance_scripts/some_maintenance_script.php
require_once ('/var/www/main_document_root/include/');

In the above example, the database connection will not be made because the call to getcwd() returns the path relative to the calling script ( /home/cron_user/maintenance_scripts ) NOT relative to the file where the getcwd() function is called.
mark dot phpnetspam at mhudson dot net
3.11.2006 22:42
This function is often used in conjuction with basename(), i.e.
hodgman at ali dot com dot au
7.09.2006 4:58
I use this code to replicate the pushd and popd DOS commands in PHP:

= array();
pushd( $dir )
array_push( $g_DirStack, getcwd() );
chdir( $dir );
popd( )
$dir = array_pop( $g_DirStack );
assert( $dir !== null );
chdir( $dir );

This allows you to change the current directory with pushd, then use popd to "undo" the directory change when you're done.
emailfire at gmail dot com
8.12.2005 15:57
To get the username of the account:

= getcwd();
$part = explode('/', $dir);
$username = $part[1];

If current directory is '/home/mike/public_html/' it would return mike.
memandeemail at gmail dot com
7.12.2005 12:48
Some server's has security options to block the getcwd()

Alternate option:

marcus at synchromedia dot co dot uk
4.05.2005 17:41
"On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does."

Just so you know, MacOS X is one of these variants (at least 10.4 is for me). You can make it work by applying 'chmod a+rx' to all folders from your site folder upwards.
vermicin at antispam dot gmail dot com
27.01.2005 12:48
If your PHP cli binary is built as a cgi binary (check with php_sapi_name), the cwd functions differently than you might expect.

say you have a script /usr/local/bin/purge
you are in /home/username

php CLI: getcwd() gives you /home/username
php CGI: getcwd() gives you /usr/local/bin

This can trip you up if you're writing command line scripts with php. You can override the CGI behavior by adding -C to the php call:

#!/usr/local/bin/php -Cq

and then getcwd() behaves as it does in the CLI-compiled version.
manux at manux dot org
22.06.2004 6:44
watch out:
working directory, and thus:
getcwd ()
is "/" while being into a register'ed shutdown function!!!
dave at corecomm dot us
10.12.2003 19:14
getcwd() returns the path of the "main" script referenced in the URL.

dirname(__FILE__) will return the path of the script currently executing.

I had written a script that required several class definition scripts from the same directory. It retrieved them based on filename matches and used getcwd to figure out where they were.

Didn't work so well when I needed to call that first script from a new file in a different directory.
fvu at wanadoo dot nl
24.11.2003 2:50
Make sure to lowercase the result before comparing Windows paths, because this function returns ambiguous results on Windows.  From within Apache, the returned path is lowercase, while from the command line interface (CLI) the returned path uses the 'real' Windows pathname.  For example, running the 'print getcwd();' command from 'C:\Program Files' returns either

   c:\program files   (Apache)
   C:\Program Files   (CLI)

When the directory is specified using chdir(), getcwd() uses the exact chdir argument.  For example:

   <?php chdir('C:\\PrOgRaM fIlEs'); print getcwd(); ?>


   C:\PrOgRaM fIlEs   (Apache & CLI)

The following code can be used to return a unambiguous lowercased cwd when running on Windows:

   <?php $sCwd = (substr(PHP_OS, 0, 3) == 'WIN') ? strtolower(getcwd()) : getcwd(); ?>
raja at rajashahed dot com
6.11.2003 19:21
This is  current working directory. X example, your document root is c:\Inetpub\www\htdocs. When You need to know what is your doc_root; /* Like ask yourself   your name ;)*/

$_cur_dir = getcwd();
echo "My doc_root is  $_cur_dir ";
// it prints out : My doc_root is c:\Inetpub\www\htdocs

/* Usually you need it after using  chdir() to know what is
running in current directory */

PHP Powered Diese Seite bei
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)