Get directory path php

dirname

Получив строку, содержащую путь к файлу или каталогу, данная функция возвратит родительский каталог данного пути.

Список параметров

На платформах Windows в качестве разделителей имен директорий используются оба слеша (прямой / и обратный \). В других операционных системах разделителем служит прямой слеш (/).

Возвращаемые значения

Возвращает путь к родительской директории. Если в параметре path не содержится слешей, будет возвращена точка (‘.‘), обозначающая текущую директорию. В другом случае будет возвращен path без последнего компонента /component.

Список изменений

Версия Описание
5.0.0 dirname() теперь безопасна для обработки бинарных данных.

Примеры

Пример #1 Пример использования функции dirname()

echo «1) » . dirname ( «/etc/passwd» ) . PHP_EOL ; // 1) /etc
echo «2) » . dirname ( «/etc/» ) . PHP_EOL ; // 2) / (или \ на Windows)
echo «3) » . dirname ( «.» ); // 3) .
?>

Читайте также:  Html5 input types javascript

Примечания

Замечание:

Функция dirname() наивно оперирует исключительно исходной строкой и не учитывает реальную файловую систему или компоненты пути типа «..«.

Замечание:

dirname() учитывает настройки локали, поэтому для корректной обработки пути с многобайтными символами должна быть установлена соответствующая локаль с помощью функции setlocale() .

Замечание:

Начиная с версии PHP 4.3.0, функция dirname() вернет слеш или точку там, где ранее возвращалась бы пустая строка.

Посмотрите следующий пример, иллюстрирующий эти изменения:

//до PHP 4.3.0
dirname ( ‘c:/’ ); // возвращала ‘.’

//после PHP 4.3.0
dirname ( ‘c:/x’ ); // возвращает ‘c:\’
dirname ( ‘c:/Temp/x’ ); // возвращает ‘c:/Temp’
dirname ( ‘/x’ ); // возвращает ‘\’

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

  • basename() — Возвращает последний компонент имени из указанного пути
  • pathinfo() — Возвращает информацию о пути к файлу
  • realpath() — Возвращает канонизированный абсолютный путь к файлу

Источник

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 .

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; 

Источник

Get Current Directory Name and Path in PHP

Get Current Directory Name and Path in PHP

  1. Use the getcwd() Function to Get the Current Directory Name in PHP
  2. Use the dirname() Function to Get the Current Directory Name in PHP
  3. Use the basename() Function to Get the Current Directory Name 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 .

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

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

Related Article — PHP File

Related Article — PHP Directory

Copyright © 2023. All right reserved

Источник

Get Root Directory Path of a PHP project?

In order to get the root directory path, you can use _DIR_ or dirname().

The second syntax is as follows−

Both the above syntaxes will return the same result.

Example

Output

AmitDiwan

  • Related Articles
  • Get all subdirectories of a given directory in PHP
  • C# Program to get the name of root directory
  • How to get root directory information in android?
  • PHP – How to get or set the path of a domain?
  • How to get file name from a path in PHP?
  • How to get full path of current file’s directory in Python?
  • Get the absolute path for the directory or file in Java
  • Find last Directory or file from a given path
  • How to Zip a directory in PHP?
  • Specify a path for a file or a directory in Java
  • How to extract a part of the file path (a directory) in Python?
  • PHP: Unlink All Files Within A Directory, and then Deleting That Directory
  • Java Program to get the File object with the absolute path for the directory or file
  • How to create a directory in project folder using Java?
  • Program for longest common directory path in Python

Annual Membership

Enjoy unlimited access on 5500+ Hand Picked Quality Video Courses

Training for a Team

Affordable solution to train a team and make them project ready.

Tutorials PointTutorials Point

  • About us
  • Refund Policy
  • Terms of use
  • Privacy Policy
  • FAQ’s
  • Contact

Copyright © Tutorials Point (India) Private Limited. All Rights Reserved.

We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy. Agree Learn more

Источник

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