Get current dir in php

Get Current Directory Name and Path in PHP

Eg: In your you need to use functions in , so you use : : That way when common.php is in , the call of in will correctly includes in instead of trying to look in current directory where is run. As a safeguard you can check if path is empty: This article will introduce a few methods to get the current working directory name in PHP.

Delete directory with files in it?

I wonder, what’s the easiest way to delete a directory with all its files in it?

I’m using rmdir(PATH . ‘/’ . $value); to delete a folder, however, if there are files inside of it, I simply can’t delete it.

There are at least two options available nowadays.

    Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example:

public static function deleteDir($dirPath) < if (! is_dir($dirPath)) < throw new InvalidArgumentException("$dirPath must be a directory"); >if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') < $dirPath .= '/'; >$files = glob($dirPath . '*', GLOB_MARK); foreach ($files as $file) < if (is_dir($file)) < self::deleteDir($file); >else < unlink($file); >> rmdir($dirPath); > 
$dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree'; $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) < if ($file->isDir())< rmdir($file->getRealPath()); > else < unlink($file->getRealPath()); > > rmdir($dir); 

I generally use this to delete all files in a folder:

array_map('unlink', glob("$dirname/*.*")); 

what’s the easiest way to delete a directory with all its files in it?

system("rm -rf ".escapeshellarg($dir)); 

Short function that does the job:

I use it in a Utils class like this:

With great power comes great responsibility : When you call this function with an empty value, it will delete files starting in root ( / ). As a safeguard you can check if path is empty:

function deleteDir($path) < if (empty($path)) < return false; >return is_file($path) ? @unlink($path) : array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path); > 

Url — how to hide .php from address bar, There are several ways of doing it. You can use mod-rewrite to rewire foo to foo.php so that requests for /bar gets handled by /bar.php. You can use directories, and default-files, so that you link to the direcory /foo/ which gets handled by /foo/index.php. You can set a php-script as the handler for 404-errors, …

Get Current Directory Name and Path in PHP

This article will introduce a few methods to get the current working directory name in PHP.

Use the getcwd() Function to Get the Current Directory Name in PHP

The getcwd() function gives the current working directory. The returned value is a string on success.

The function does not take any parameters. The function returns false in case of failure.

Let’s consider the following directory structure.

├── var │ └── www │ └── html | └──project | └──index.php 

The PHP File lies inside the project directory. The getcwd() function will return the name of the current working directory, which is project .

Читайте также:  Дандер методы python это

We can use the echo function to display the content of the function. We can see in the output section that the getcwd() function returns the current working directory with its path.

Use the dirname() function to get the current Directory Name in PHP

We can also use the dirname() function to get the current directory name in PHP. The function returns the path of the parent directory.

It accepts two parameters where the first one is the path and the second one is levels. Levels indicate the number of directories to move up.

Finally, we can use the __FILE__ magic constants in the dirname() function to get the name of the current directory. The __FILE__ constant returns the full path of the current file along with the file name.

We can demonstrate these constants and the function in the above directory structure. For example, we get the following result when we echo the __FILE__ constant from the index.php file.

/var/www/html/project/index.php 

For example, write the dirname() function in the index.php file with the __FILE__ constant as the parameter.

In this way, we can get the current working directory name in PHP.

Use the basename() Function to Get the Current Directory Name in PHP

We can use the basename() function to get the current working directory name without the path in PHP. We can apply this function with the result of the above two functions.

The basename() function returns the name of the base file or folder from the given path. For example, if the path provided is /var/www/html/project , the output will be project .

For example, use the functions dirname(__FILE__) and getcwd() as the parameters for the basename() function. In this way, we can get the current working directory name in PHP.

echo basename(dirname(__FILE__))."
"; echo basename(getcwd())."\n";

PHP File

Pget arent path php from array paths Code Example, // dirname ( string $path [, int $levels = 1 ] ) : string

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; 

Источник

getcwd

Returns the current working directory on success, or false on failure.

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. See chmod() for more information on modes and permissions.

Examples

Example #1 getcwd() example

// current directory
echo getcwd () . «\n» ;

// current directory
echo getcwd () . «\n» ;

The above example will output something similar to:

If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled, the current working directory returned by getcwd() may be different from that returned by operating system interfaces. External libraries (invoked through FFI) which depend on the current working directory will be affected.

Читайте также:  Color supported by html

See Also

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

Читайте также:  Make forms with php

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

Источник

Оцените статью