Php имя текущей папки

getcwd

Возвращает текущий рабочий каталог в случае успешного выполнения или false в случае ошибки.

На некоторых вариантах Unix getcwd() вернёт false , если на каком-либо из родительских каталогов не установлен режим чтения или поиска, даже если он установлен на текущем каталоге. Больше информации о режимах доступа смотрите в документации функции chmod() .

Примеры

Пример #1 Пример использования getcwd()

// текущий каталог
echo getcwd () . «\n» ;

// текущий каталог
echo getcwd () . «\n» ;

Результатом выполнения данного примера будет что-то подобное:

Если PHP-интерпретатор собран с поддержкой ZTS (Zend Thread Safety), текущий рабочий каталог, возвращаемый getcwd() , может отличаться от того, что возвращают интерфейсы операционной системы. Буду задействованы внешние библиотеки (подключённые через FFI), использующие текущий рабочий каталог.

Смотрите также

User Contributed Notes 20 notes

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.

given a link
/some/link->/some/location/path

with linux bash,
if within the linked drawer /some/link
cd .. goes upper link /some/
cd -P .. goes upper destination /some/location/

with php
fopen («../file») goes upper destination /some/location/file

some others commented about ways obtaining the path below.

I found some luck with using $_SERVER[‘DOCUMENT_ROOT’] instead
to recraft an absolute path.

getcwd() appears to call the equivalent of PHP’s realpath() on the path. It never returns symlinks, but always the actual directory names in the path to the current working directory.

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 () global $argv ;
$dir = dirname ( getcwd () . ‘/’ . $argv [ 0 ]);
$curDir = getcwd ();
chdir ( $dir );
$dir = getcwd ();
chdir ( $curDir );
return $dir ;
>
?>
So you can use it like this:
include get_file_dir () . ‘/otherfile.php’ ;
// or even..
chdir ( get_file_dir ());
include ‘./otherfile.php’ ;
?>
Spent some time thinking this one out, maybe it helps someone 🙂

I use this code to replicate the pushd and popd DOS commands in PHP:

$g_DirStack = array();
function pushd ( $dir )
global $g_DirStack ;
array_push ( $g_DirStack , getcwd () );
chdir ( $dir );
>
function popd ( )
global $g_DirStack ;
$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.

This function is often used in conjuction with basename(), i.e.
http://www.php.net/manual/en/function.basename.php

Some server’s has security options to block the getcwd()

«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.

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

chdir ( $path );
return gstr_replace ( ‘\\’ , ‘/’ , getcwd ());

//change the cwd back to the old value to not interfere with the script
chdir ( $oldcwd );

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

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

It appears there is a change in functionality in PHP5 from PHP4 when using the CLI tool. Here is the example: —

PHP4 returns /tmp
PHP5 returns /

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.

example:
//in /var/www/main_document_root/include/MySQL.inc.php
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/MySQL.inc.php’ );
?>

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.

Be aware when calling getcwd() in directories consisting of symlinks.

getcwd() is the equivalent of shell command «pwd -P» which resolves symlinks.

The shell command «pwd» is the equivalent of «pwd -L» which uses PWD from the environment without resolving symlinks. This is also the equivalent of calling getenv(‘PWD’).

As you could read in
http://www.php.net/manual/en/features.commandline.differences.php
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:

chdir ( 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 );

Источник

Смотрите также

За описанием сопутствующих функций, таких как dirname() , is_dir() , mkdir() и rmdir() , обратитесь к главе Файловая система.

User Contributed Notes 7 notes

I wrote a simple backup script which puts all files in his folder (and all of the sub-folders) in one TAR archive.
(It’s classic TAR format not USTAR, so filename and path to it can’t be longer then 99 chars)
/***********************************************************
* Title: Classic-TAR based backup script v0.0.1-dev
**********************************************************/

Class Tar_by_Vladson var $tar_file ;
var $fp ;
function Tar_by_Vladson ( $tar_file = ‘backup.tar’ ) $this -> tar_file = $tar_file ;
$this -> fp = fopen ( $this -> tar_file , «wb» );
$tree = $this -> build_tree ();
$this -> process_tree ( $tree );
fputs ( $this -> fp , pack ( «a512» , «» ));
fclose ( $this -> fp );
>
function build_tree ( $dir = ‘.’ ) $handle = opendir ( $dir );
while( false !== ( $readdir = readdir ( $handle ))) if( $readdir != ‘.’ && $readdir != ‘..’ ) $path = $dir . ‘/’ . $readdir ;
if ( is_file ( $path )) $output [] = substr ( $path , 2 , strlen ( $path ));
> elseif ( is_dir ( $path )) $output [] = substr ( $path , 2 , strlen ( $path )). ‘/’ ;
$output = array_merge ( $output , $this -> build_tree ( $path ));
>
>
>
closedir ( $handle );
return $output ;
>
function process_tree ( $tree ) foreach( $tree as $pathfile ) if ( substr ( $pathfile , — 1 , 1 ) == ‘/’ ) fputs ( $this -> fp , $this -> build_header ( $pathfile ));
> elseif ( $pathfile != $this -> tar_file ) $filesize = filesize ( $pathfile );
$block_len = 512 * ceil ( $filesize / 512 )- $filesize ;
fputs ( $this -> fp , $this -> build_header ( $pathfile ));
fputs ( $this -> fp , file_get_contents ( $pathfile ));
fputs ( $this -> fp , pack ( «a» . $block_len , «» ));
>
>
return true ;
>
function build_header ( $pathfile ) if ( strlen ( $pathfile ) > 99 ) die( ‘Error’ );
$info = stat ( $pathfile );
if ( is_dir ( $pathfile ) ) $info [ 7 ] = 0 ;
$header = pack ( «a100a8a8a8a12A12a8a1a100a255» ,
$pathfile ,
sprintf ( «%6s » , decoct ( $info [ 2 ])),
sprintf ( «%6s » , decoct ( $info [ 4 ])),
sprintf ( «%6s » , decoct ( $info [ 5 ])),
sprintf ( «%11s » , decoct ( $info [ 7 ])),
sprintf ( «%11s» , decoct ( $info [ 9 ])),
sprintf ( «%8s» , » » ),
( is_dir ( $pathfile ) ? «5» : «0» ),
«» ,
«»
);
clearstatcache ();
$checksum = 0 ;
for ( $i = 0 ; $i < 512 ; $i ++) $checksum += ord ( substr ( $header , $i , 1 ));
>
$checksum_data = pack (
«a8» , sprintf ( «%6s » , decoct ( $checksum ))
);
for ( $i = 0 , $j = 148 ; $i < 7 ; $i ++, $j ++)
$header [ $j ] = $checksum_data [ $i ];
return $header ;
>
>

header ( ‘Content-type: text/plain’ );
$start_time = array_sum ( explode ( chr ( 32 ), microtime ()));
$tar = & new Tar_by_Vladson ();
$finish_time = array_sum ( explode ( chr ( 32 ), microtime ()));
printf ( «The time taken: %f seconds» , ( $finish_time — $start_time ));
?>

Here is a very similar function to *scandir*, if you are still using PHP4.

This recursive function will return an indexed array containing all directories or files or both (depending on parameters). You can specify the depth you want, as explained below.

// $path : path to browse
// $maxdepth : how deep to browse (-1=unlimited)
// $mode : «FULL»|»DIRS»|»FILES»
// $d : must not be defined

function searchdir ( $path , $maxdepth = — 1 , $mode = «FULL» , $d = 0 )
if ( substr ( $path , strlen ( $path ) — 1 ) != ‘/’ ) < $path .= '/' ; >
$dirlist = array () ;
if ( $mode != «FILES» ) < $dirlist [] = $path ; >
if ( $handle = opendir ( $path ) )
while ( false !== ( $file = readdir ( $handle ) ) )
if ( $file != ‘.’ && $file != ‘..’ )
$file = $path . $file ;
if ( ! is_dir ( $file ) ) < if ( $mode != "DIRS" ) < $dirlist [] = $file ; >>
elseif ( $d >= 0 && ( $d < $maxdepth || $maxdepth < 0 ) )
$result = searchdir ( $file . ‘/’ , $maxdepth , $mode , $d + 1 ) ;
$dirlist = array_merge ( $dirlist , $result ) ;
>
>
>
closedir ( $handle ) ;
>
if ( $d == 0 ) < natcasesort ( $dirlist ) ; >
return ( $dirlist ) ;
>

I would like to present these two simple functions for generating a complete directory listing — as I feel the other examples are to restrictive in terms of usage.

Usage is as simple as this:
$dir = «»;
$arDirTree = dirTree($dir);
printTree($arDirTree);

It is easy to add files to the tree also — so enjoy.

To join directory and file names in a cross-platform manner you can use the following function.

function join_path()
$num_args = func_num_args();
$args = func_get_args();
$path = $args[0];

It should do the following:
$src = join_path( ‘/foo’, ‘bar’, ‘john.jpg’ );
echo $src; // On *nix -> /foo/bar/john.jpg

$src = join_path( ‘C:\www’, ‘domain.com’, ‘foo.jpg’ );
echo $src; // On win32 -> C:\\www\\domain.com\\foo.jpg

Samba mounts under a Windows environment are not accessible using the mounted drive letter. For instance, if you have drive X: in Windows mounted to //example.local/shared_dir (where example.local is a *nix box running Samba), the following constructs

$dir = «X:\\data\\»;
$handle = opendir( $dir );
or
$d = dir( $dir );

will return a warning message «failed to open dir: No error»

On the other hand, using the underlying mapping info works just fine. For example:

$dir = «//example.local/shared_dir/data»;
$handle = opendir( $dir );
or
$d = dir( $dir );

Both cases do what they’re expected to.

Mine works as long as the samba volume is actually mounted. Having it listed in the «My Computer» window doesn’t warrant that.

I have posted this same observation in scandir, and found out that it is not limited to scandir alone but to ALL directory functions.

Directory functions DOES NOT currently supports Japanese characters.

Источник

Читайте также:  Python pywallet py dumpwallet datadir
Оцените статью