узнать текущую директорию php
PHP Текущее местоположение скрипта, папки, имя файла
В языке PHP есть несколько полезных констант, которые мы можем применять в построении динамического пути к файлу или папке.
Как в PHP узнать полный путь к файлу или папке
Для начала приведу примеры, что вы получите вызвав соответствующие константы:
Мы рассмотрели 2 константы, __FILE__ и __DIR__ для отображения полного пути к текущему файлу и папке (директории). Стоит отметить, что __DIR__ эквивалентен вызову:
dirname — это стандартная функция PHP, которая возвращает родительский каталог. Она применяется как раз для таких ситуаций, когда вам нужно узнать полный путь к файлу без самого файла :). Мне на ум пришла идея, как можно добиться такого же результата (не удивлюсь, если под капотом тоже самое):
Что мы еще можем применить для константы __FILE__? Конечно же отделить путь и получить просто имя файла:
basename — функция возвращает последний элемент из пути, который, как правило, и является именем файла. Раз уж мы решили писать функции заменители, давайте рассмотрим наш URL, как массив, разделенный слешами («/»):
Как видим, последний элемент массива является нашим файлом. Чтобы получить последний элемент массива, не зная его количество, пишем:
Минус 1 потому как отсчет для массивов идет с нуля, но при счете всегда стартует с единицы.
Важно — в некоторых указаниях полного пути вы используете разделители (вышеупомянутые слеши ‘/’). Но, для Windows это «\», для Linux и остальных — «/». Есть такая константа:
Вернет 1 слеш (без кавычек).
Немного закрепим 2 функции, о которых шла речь выше:
str_replace — функция, которая используется для замены в строке. Первый параметр «что ищем», затем «на что меняем» и последний «где ищем», в который мы и передали нашу полную строку.
explode — функция, которая делает из строки массив. Но, чтобы функции понять как разбить строку — ей нужно передать «разделитель», а уже вторым параметром — саму строку.
Как вы заметили, «/home/bitrix/www» — это путь на самом сервере, который можно «вырезать» как раз при помощи str_replace.
Если вам нужно использовать «текущий домен», то получить его при помощи PHP можно несколькими способами. Один из них:
Надеюсь вам эта тема была интересна. Пишите в комментариях как вам формат, и нужен ли он вообще. А то в последнее время только битрикс да битрикс :).
автор: Dmitriy
Занимаюсь веб-разработкой с 2011 года. Посмотреть некоторые из моих работ, а также узнать чуть больше обо мне, вы можете на forwww.ru.
— Создание сайтов на 1С-Битрикс любой сложности
— Вёрстка макетов Figma, Photoshop, Zeplin
— Поддержка проектов на Битриксе
— Разработка нового функционала для сайта
— Парсинг данных
— Выгрузка из файлов в формате XML, YML, XLS, XLSX, CSV, JSON
— Интеграция по API со сторонними сервисами
и многое другое
Каталоги
Получение файлов из каталога
Сначала рассмотрим современный способ получения файлов. Он появился в версии PHP 5. Функция scandir() возвращает массив, содержащий имена каталогов и файлов в указанном каталоге.
scandir (адрес, сортировка, контекст)
Указанные константы для сортировки появились, начиная с версии PHP 5.4.0. В предыдущих версиях сортировка указывалась по другому. Любое значение, отличное от нулевого, определяет сортировку по убыванию, а 0 сортировку по возрастанию.
В массиве, который возвращает функция, кроме имён файлов и директорий, всегда есть два значения: «.» и «..». Одна точка означает текущий каталог, а две точки означают родительский каталог.
Для примера создадим в папке со скриптами папку с именем mydirectory. Скопируем в неё несколько файлов. Выведем на страницу список файлов из директории.
Выбор каталога
Часто возникает необходимоть работать с текущим каталогом, то есть с тем, в котором находится скрипт. Для выбора этого каталога не обязательно указывать абсолютный адрес. Можно указать по-другому. Одна точка означает текущую директорию, а две точки означают родительскую директорию. Пример:
Функция getcwd() возвращает адрес текущей директории.
Создание, перемещение и удаление каталога
Функция mkdir() создаёт новый каталог. Возвращает true в случае успеха.
mkdir (адрес, режим доступа, вложенные каталоги, контекст)
Обязателен только первый параметр.
Создадим в текущем каталоге новый каталог. Учитывайте, что в 6 строке текущим был выбран другой каталог.
Функция rmdir() удаляет каталог. При этом он должен быть пустым. Если он не пустой, то сначала нужно переместить или удалить из него все файлы. Функция возвращает true при успешном удалении.
Коприрование материалов сайта возможно только с согласия администрации
getcwd
(PHP 4, PHP 5, PHP 7, PHP 8)
getcwd — Получает имя текущего рабочего каталога
Описание
Возвращает имя текущего рабочего каталога.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает текущий рабочий каталог в случае успешного выполнения или false в случае ошибки.
Примеры
Пример #1 Пример использования getcwd()
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
User Contributed Notes 19 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.
I use this code to replicate the pushd and popd DOS commands in PHP:
«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.
PHP4 returns /tmp
PHP5 returns /
Something to be aware of.
This is a function to convert a path which looks something like this:
To a proper directory 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
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
Some server’s has security options to block the getcwd()
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.
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:
// 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 ( ‘
// how to switch symlink-free to the folder the current file resides in:
chdir ( dirname ( realpath ( __FILE__ ) ) );
// how to get a path one folder up in any case :
$my_parent_folder = preg_replace ( ‘
dirname
(PHP 4, PHP 5, PHP 7, PHP 8)
dirname — Возвращает имя родительского каталога из указанного пути
Описание
Получив строку, содержащую путь к файлу или каталогу, данная функция возвратит родительский каталог данного пути на levels уровней вверх.
В Windows dirname() предполагает текущую установленную кодовую страницу, поэтому для того, чтобы видеть правильное имя каталога с путями многобайтовых символов, необходимо установить соответствующую кодовую страницу. Если path содержит символы, недопустимые для текущей кодовой страницы, поведение dirname() не определено.
В других системах dirname() предполагает, что path закодирован в кодировке, совместимой с ASCII. В противном случае поведение функции не определено.
Список параметров
На платформах Windows в качестве разделителей имён директорий используются оба слеша (прямой / и обратный \ ). В других операционных системах разделителем служит прямой слеш ( / ).
На сколько уровней вложенности вверх необходимо пройти.
Должно быть целым числом больше 0.
Возвращаемые значения
Список изменений
Примеры
Пример #1 Пример использования функции dirname()
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
User Contributed Notes 29 notes
To get the directory of current included file:
( __FILE__ );
?>
For example, if a script called ‘database.init.php’ which is included from anywhere on the filesystem wants to include the script ‘database.class.php’, which lays in the same directory, you can use:
Since the paths in the examples given only have two parts (e.g. «/etc/passwd») it is not obvious whether dirname returns the single path element of the parent directory or whether it returns the whole path up to and including the parent directory. From experimentation it appears to be the latter.
returns ‘/usr/local/magic’ and not just ‘magic’
Also it is not immediately obvious that dirname effectively returns the parent directory of the last item of the path regardless of whether the last item is a directory or a file. (i.e. one might think that if the path given was a directory then dirname would return the entire original path since that is a directory name.)
Further the presense of a directory separator at the end of the path does not necessarily indicate that last item of the path is a directory, and so
dirname(‘/usr/local/magic/bin/’); #note final ‘/’
would return the same result as in my example above.
In short this seems to be more of a string manipulation function that strips off the last non-null file or directory element off of a path string.
I ran into this when I wrote a site on a url with a path, www.somehost.com/client/somepage.php, where the code above works great, but then wanted to put it on a subdomain, client.somehost.com/somepage.php, where things started breaking.
The best solution would be to create a function that generates absolute URLs and use that throughout the site, but creating a safe_dirname function (and an htaccess rewrite to fix double-slashes just in case) fixed the issue for me:
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache:
File located locally in: F:\localhost\www\Shaz3e-ResponsiveFramework\S3-CMS\_source
Example 1: dirname($_SERVER[‘PHP_SELF’]); //output: /Shaz3e-ResponsiveFramework/S3-CMS/_source
Getting absolute path of the current script:
( __FILE__ )
?>
Getting webserver relative path of the current script.
( dirname ( __FILE__ ));
?>
If anyone has a better way, get to the constructive critisism!
You can use it to get parent directory:
. include a file relative to file path:
Inside of script.php I needed to know the name of the containing directory. For example, if my script was in ‘/var/www/htdocs/website/somedir/script.php’ i needed to know ‘somedir’ in a unified way.
The solution is:
= basename ( dirname ( __FILE__ ));
?>
Expanding on Anonymous’ comment, this is not necessarily correct. If the user is using a secure protocol, this URL is inaccurate. This will work properly:
A simple way to show the www path to a folder containing a file.
The same function but a bit improved, will use REQUEST_URI, if not available, will use PHP_SELF and if not available will use __FILE__, in this case, the function MUST be in the same file. It should work, both under Windows and *NIX.
The best way to get the absolute path of the folder of the currently parsed PHP script is:
?>
This will result in an absolute unix-style path which works ok also on PHP5 under Windows, where mixing ‘\’ and ‘/’ may give troubles.
[EDIT by danbrown AT php DOT net: Applied author-supplied fix from follow-up note.]
dirname can be used to create self referencing web scripts with the following one liner.
A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.
In some situations (I can’t locate the dependencies) basename and dirname may return incorrect values if parsed string is in UTF-8.
Like, dirname(«glossary/задний-фокус») will return «glossary» and basename(«glossary/задний-фокус») will return «-фокус».
Most mkpath() function I saw listed here seem long and convoluted.
Here’s mine:
If you want to get the parent parent directory of your script, you can use this:
this little function gets the top level public directory
In my mvc based framework i make BASE_PATH and BASE_URL definitions like the following and both work well in the framework without problem.
BASE_PATH is for server side inclusions.
BASE_URL is for client side inclusions (scripts, css files, images etc.)
Code for write permissions check:
If you merely want to find out wether a certain file is located within or underneath a certain directory or not, e.g. for White List validation, the following function might be useful to you:
You can get best root path if you want to call a file from you project paths.
Make sure this define in your www/index.php
or the core file that inside www/ root.
?>
You can call any file any time without any problems
A nice «current directory» function.
function current_dir()
<
$path = dirname($_SERVER[PHP_SELF]);
$position = strrpos($path,’/’) + 1;
print substr($path,$position);
>
I find this usefull for a lot of stuff! You can maintain a modular site with dir names as modules names. At least I would like PHP guys to add this to the function list!
If there is anything out there like it, please tell me.
realpath
(PHP 4, PHP 5, PHP 7, PHP 8)
realpath — Возвращает канонизированный абсолютный путь к файлу
Описание
Список параметров
Несмотря на то, что путь должен быть указан, переданное значение может быть пустой строкой. В этих случаях значение интерпретируется как текущая рабочая директория.
Возвращаемые значения
realpath() возвращает false при неудаче, например, если файл не существует.
Для регистронезависимых файловых систем, realpath() может нормализовать или не нормализовать регистр символов.
Функция realpath() не будет работать с файлом внутри архива Phar, так как путь может быть не реальным, а виртуальным.
В Windows переходы и символические ссылки на каталоги расширяются только на один уровень.
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Примеры
Пример #1 Пример использования функции realpath()
Результат выполнения данного примера:
Пример #2 realpath() на Windows
На Windows realpath() изменит пути стиля Unix на стиль Windows.
echo realpath ( ‘/windows/system32’ ), PHP_EOL ;
echo realpath ( ‘C:\Program Files\\’ ), PHP_EOL ;
?>
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 15 notes
As you can so, it also produces Yoda-speak. 🙂
realpath() is just a system/library call to actual realpath() function supported by OS. It does not work on a path as a string, but also resolves symlinks. The resulting path might significantly differs from the input even when absolute path is given. No function in this notes resolves that.
namespace MockingMagician \ Organic \ Helper ;