Войны между программистами php и perl кажется давно уже позади. Даже я стал программировать на php, напрочь забыв perl. Но это не значит, что меня всё устраивает в php. Например то, что скрипты на php могут не только легко содержать куски html-разметки, но и запускаться из любой папки на сервере, я до сих пор считаю серьёзной уязвимостью, накладывающей дополнительные обязательства на программиста, пишущего код. Наверняка, можно озадачится и серверными средствами ограничить запуск php-скриптов из всех директорий, кроме выбранной, (или, по крайней мере, прописать в правах доступа к папкам запрет на исполнение с наследованием этого свойства файлами), но я пока не встречал кода, который показал бы, что этим кто-то озадачивался. Как использовать эту особенность php, я для себя решил. А в этой статье рассмотрим, как подняться по всему дереву каталогов в корневую директорию с помощью php-скрипта, который, как увидим, может спокойно лазить по всему серверу и что-то там себе в делать тихим сапом (в зависимости от развитости и извращённости фантазии программиста, его написавшего).
Для начала рассмотрим две глобальные переменные php и одну функцию, которые позволяют быстро с помощью языка программирования определить место, где находится скрипт в дереве каталогов на сервере. Эксперимента ради, я загрузил скрипт глубоко в папки установленной Joomla, на которой работает этот сайт.
Итак, скрипт с названием delete.php (потому что после написания статьи будет удалён) лежит в папке \www\mb4.ru\templates\protostar\html\layouts\joomla\html\batch\, если рассматривать его путь от домашней директории пользователя.
В php версиях: PHP 4 >= 4.1.0, PHP 5, PHP 7 есть переменная $_SERVER, содержащая в себе массив с заголовками, путями и местоположениями скриптов. Записи в этом массиве создаются веб-сервером. Нет гарантии, что каждый веб-сервер предоставит любую информацию, но по умолчанию, рассматриваемые ниже два пути, хранящиеся в этом массиве, отдаются сервером «на ура».
$_SERVER['DOCUMENT_ROOT']- в этой переменной содержится директория корня документов, в которой выполняется текущий скрипт, в точности та, которая указана в конфигурационном файле сервера.
$_SERVER['SCRIPT_FILENAME']- в этой переменной содержится абсолютный путь к исполняемому скрипту.
Для проверки, как это работает, достаточно запустить php-скрипт, который выдаст на экран содержимое этих переменных:
<?php
echo "$_SERVER['DOCUMENT_ROOT'] . "<br>";
echo "$_SERVER['SCRIPT_FILENAME']";
?>В результате получим нечто подобное:
То есть корневую папку пользователя, под которым запущен на выполнение скрипт и ВНИМАНИЕ (!) — полный путь к исполняемому скрипту от корня дерева каталогов сервера (!). Красота 😉
В php есть ещё одна полезная функция, которой мы воспользуемся ниже для подъёма к корню файловой системы сервера, которая получает имя текущего рабочего каталога. Это функция getcwd(), работающая во всех версиях php (PHP 4, PHP 5, PHP 7).
То есть, запустив код:
<?php
echo "getcwd()";
?>Получим в качестве выполнения:
Всё тот же путь, по которому можно подняться до корня файловой системы.
- How to create a folder above the root directory using php
- Command run folder from root directory
- Copy file from one folder to root directory
- Php get root from sub directory php
- Php php make directory in different folder
- Command run folder from root directory code example
- Tomcat root directory/working folder for webapp
- How to create folder in «root directory» with Flutter?
- Get size of folders on root directory [duplicate]
- Php how to access root folder in php
- Recursively scan all the directories under the root directory and find only the newest file from each folder
- Change site root directory with php
- Php created in the root directory
- Zip with php in root directory
- Php access php in root directory
- Php php site root directory code example
- Php how to define root directory in php
- Upload image to root directory from sub directory php
- How do i open a folder as root
- Cd .. on root folder
- HTML root folder?
- Using scandir() to find folders in a directory (PHP)
- Shell php list all folders in directory
- How to Move Files and Folders from One Directory to Another Using PHP
- Ubuntu hange directory to the repo root folder
- How to create a folder and a file in my project root directory
- What’s the PHP $_SERVER variable for the directory above DOCUMENT_ROOT?
- PHP using $_SERVER[«DOCUMENT_ROOT»] and relative or absolute paths
- When should i use my own defined webroot and server root
- How can I control DOCUMENT_ROOT to work on localhost and live server?
- Description
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- Описание
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Смотрите также
- Описание
- Индексы
- Примеры
- Примечания
- What is file system root?
- Where or how to find the document root when launching localhost
- Php build in server is not showing document root
- What is root folder in HTML?
- PHP built in webserver and Document root folder
- Как подняться к корню каталога с помощью php, заходя в каждую папку
- What is meant by root directory?
- What is a root directory of a website?
- How can I get root URL in php?
- How do I set the root directory?
- Where is my php directory?
- Резюме
- Как получить список папок ветки дерева каталога, в котором лежит php-скрипт
How to create a folder above the root directory using php
It may be worthwhile to restructure the directories within your root directory to simulate, problem is it recognizes public folder as root directory., as root directory ?, class root directory
just like wordpress does?, When you ask for a file (with require, or include), PHP will try to find it in the current directory.
Command run folder from root directory
Root
Folder A
Folder 1
file1.jpg
file2.jpg
Folder 2
file3,
Is there a way to run the command from the Folder Root and recursively scroll to A, B and,
Execute moveToRootBase.bat from Folder Root and done!
, This one unlike the other three provides the root directory of the
Copy file from one folder to root directory
$(TargetPath)
to the update_agent.bat, which is a batch file stored in the root, Solution:
try add the output path varaible to the destination folder, under it’s own folder) for assemblies — much like a web application looks for /bin.,
But, if the dll’s are not in the same directory as the executable is, they won’t be loaded,
<Target Name=»MakeMyDir» AfterTargets=»Build»>
<MakeDir Directories=»$(
Php get root from sub directory php
Php php make directory in different folder
Command run folder from root directory code example
» or distinguishing between «working directory and project root», because almost no tool is prepared, the root directory of my project., is enough to identify your project root directory, then, you can have this kind of function to get your, project root directory:
function!, The script doesn’t execute in the destination folder, as you might expect.
Tomcat root directory/working folder for webapp
the root directory is tomcat/bin folder., » is the root of the Tomcat installation directory.,
EDIT:
I located the ROOT folder., Another issue that I am facing is that my PHP page does not work here.,
So, tomcat will unpack the war and will create the folder ROOT for it.
How to create folder in «root directory» with Flutter?
Get size of folders on root directory [duplicate]
/pre>
Then to narrow down results you could replace
/
with any folder,
I have edited the command with the suggestion from muru, and now this will include dot folders, if scanning something like your home directory., and renders the total of all of them, but excludes the hidden folders in the estimation., and renders the total of all of them, and also includes the hidden folders in the estimation.
Php how to access root folder in php
directory path of a PHP project:
For PHP >= 5.3.0
use, This directory name does not have a trailing slash unless it is the root directory.,
Solution 1:
To return the folder of current, php file, use this script., You can use this to get a URL to your downloads folder.
Recursively scan all the directories under the root directory and find only the newest file from each folder
(including root):
var rootDirFile = Directory
.EnumerateFiles(yourPath, «*.*»,
In content for developers, use
root directory,
not
home directory, ,
to refer to the directory or folder from which all other directories or folders branch., Don’t shorten to
root
when you mean the directory., For example, If I run
ls /
command, I got all the directories under root.
Change site root directory with php
Php created in the root directory
Zip with php in root directory
Php access php in root directory
>server’s root directory i.e., >root folder., and point to the
/root/uploads
directory.,
Directory structure example:
root
— backend
— web
— uploads -, >accessing files from different directory which is outside root directory.
Php php site root directory code example
Php how to define root directory in php
For example, if your configuration file is in the root directory you can use:
$config,
In linux /mysite will try to access the directory in the root level of file system., (ROOT.», -d
# Change ‘subfolder’ to be the folder you will use for your primary domain., directory of an apache server?
Upload image to root directory from sub directory php
How do i open a folder as root
Cd .. on root folder
, typed at root folder, does not warn or fails with an error?, directory is interpreted to mean the root directory itself., Thus, dot-dot cannot be used to access files outside the subtree rooted at the root directory., >root directories aren’t always root directories., so I have it set up to only look for the nearest folder with a
.gitignore
HTML root folder?
folder and then into a directory from there., directory tree.,
Question:
Hello I’m trying to set the root folder of a
Using scandir() to find folders in a directory (PHP)
Shell php list all folders in directory
How to Move Files and Folders from One Directory to Another Using PHP
Ubuntu hange directory to the repo root folder
How to create a folder and a file in my project root directory
Table of contents
What’s the PHP $_SERVER variable for the directory above DOCUMENT_ROOT?
The function identified as is capable of working on any platform and is responsible for returning the parent directory of a specified directory.
dirname()
dirname($_SERVER['DOCUMENT_ROOT']);/var/www/example.com In case you require the trailing slash, you can add at the end.
DIRECTORY_SEPARATOR
dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR;If you require assistance with Windows directory naming, you will need to eliminate the final part of the path. Typically, you would accomplish this through regular expression by capturing everything except the last filepathbit/. However, to accommodate Windows naming, you must make it more sophisticated to handle both filepathbit/ and filepathbit.
PHP using $_SERVER[«DOCUMENT_ROOT»] and relative or absolute paths
$baseDir = dirname(__DIR__);
$cssFile = $baseDir."/assets/css/style.css";
$jsFile = $baseDir."/assets/js/index.js";When should i use my own defined webroot and server root
It appears that you may be making things more complex than they need to be. Here’s a simpler way to construct the path:
$_SERVER['DOCUMENT_ROOT'] . "/your/path/here" To add a to your script, begin by placing it at the top.
require_once
require_once($_SERVER['DOCUMENT_ROOT'] . "/your/path/here.php") 
Starting from the root, constructs the pathway.
/
Your confusion lies in mixing up the server path and the path of the URL.
The files on your server can be found at , while your web browser shows them as being at
C:/xampp/htdocs/folder_name
. However, the browser is unaware that the files are actually located in
http://localhost/folder_name
when loading them.
C:/xampp/htdocs/
Kindly note that the code you are using will not provide you with the «web root» directory.
The path of the file on the server can be obtained using , which will display a result similar to
__FILE__
.
`C:/xampp/htdocs/include/header.php
$serverRoot = $_SERVER['DOCUMENT_ROOT'];
$webRoot = ($_SERVER['HTTPS'] ? 'https://' : 'http://') . $_SERVER['SERVER_NAME']; An alternative option is to utilize the as the root directory for your website.
/

should be equivalent.
Give a try and you’ll receive enjoyable information.
var_dump($_SERVER);
To obtain the «sub folder» within the «root folder,» employ the . The prior instruction retrieves the primary root.
dirname
$serverPath = dirname(__FILE__); // or __DIR__
$webPath = dirname($_SERVER['PHP_SELF']);How can I control DOCUMENT_ROOT to work on localhost and live server?
Create a file in the root directory of your application and insert the code. Then, ensure that it loads on each page.
Irrespective of whether your local copy is located in a sub-directory or not, you can always execute .
$path = ABSPATH . '/path/to/file.php';
To implement the code, you can add it to a file that is already included on every page load within your application.
Please keep in mind that you might need to include more requests based on the location of the file. For every directory that you traverse from the root of your web application, add an additional request.
dirname()
Suppose your webapp is situated at , while the "global include" is present at
/webapp/
. In this case, the provided code requires some modifications.
/webapp/includes/framework/init.php
define('ABSPATH', dirname(dirname(dirname(__FILE__)))); Two more calls of were made as a result of two extra folders added to the web application root directory (
dirname()
).
includes/framework
The code mentioned should exist in a single file and be included on every page load in your web application.
If there is a file that is included prior to processing, such as a configuration file, you can simply duplicate and insert the code into that file.
The quantity of calls relies on the level of the file where you pasted the code in comparison to the root directory of your web application, which is symbolized by
dirname()
in the given examples.
~
By inserting my code into , you only require a single
~/abspath.php
call.
dirname()
By inserting my code into , you will need to make two calls to
~/includes/abspath.php
.
dirname()
Assuming you paste my code in , using it in its ultimate position will necessitate three
~/includes/config/abspath.php
calls.
dirname()
Here are the actions to be taken in .
~/index.php
You can avail the through your accessibility.
ABSPATH
You can reach through your available channels.
ABSPATH
To avoid unnecessary complexity, it is recommended to add the above code to a file that is already included on every page load. Be sure to adjust the number of calls as needed. It is important to note that this code should only be present in a single file.
dirname()
$_SESSION["uploads_base_url"]=dirname(__FILE__); You can utilize this feature for file uploads in any applicable file.
echo $uploads_base_url=$_SESSION["uploads_base_url"];
Read other technology post:
How can I control the width of JTextFields in Java Swing?
(PHP 4, PHP 5, PHP 7, PHP 8)
— Returns a parent directory’s path
Description
(, $levels):
operates naively on the input string,
and is not aware of the actual filesystem, or path components such
as «..«.
On Windows, assumes the currently set codepage, so for it to see the
correct directory name with multibyte character paths, the matching codepage must
be set.
If path contains characters which are invalid for the
current codepage, the behavior of is undefined.
On other systems, assumes path
to be encoded in an ASCII compatible encoding. Otherwise the behavior of the
the function is undefined.
Parameters
-
path On Windows, both slash (
/) and backslash
(\) are used as directory separator character. In
other environments, it is the forward slash (/).-
levels The number of parent directories to go up.
This must be an integer greater than 0.
Return Values
Returns the path of a parent directory. If there are no slashes in
path, a dot (‘.‘) is returned,
indicating the current directory. Otherwise, the returned string is
path with any trailing
/component removed.
Be careful when using this function in a loop that can reach the
top-level directory as this can result in an infinite loop.
// Will return '.'.
// Will return `\` on Windows and '/' on *nix systems.
// Will return `\` on Windows and '.' on *nix systems.
// Will return 'C:\' on Windows and '.' on *nix systems.
Changelog
Examples
Example #1 example
The above example will output
something similar to:
/etc / (or \ on Windows) . C:\ /usr
See Also
y dot a dot dejong at singular dot of dot alumni dot utwente dot nl ¶
8 years ago
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
tobylewis at mac dot com ¶
18 years ago
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.
tapken at engter dot de ¶
21 years ago
To get the directory of current included 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:
joe dot naylor at gmail dot com ¶
14 years ago
However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'. If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php.
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:
klugg this-is-junk at tlen dot pl ¶
17 years ago
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache:
ts at dev dot websafe dot pl ¶
15 years ago
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:
14 years ago
nhl261 at yahoo dot com ¶
12 years ago
As usual, to include or require a file, we use this
in rare case, we have current file existing at the root directory, dirname would return C:\ or / , then the line above contains 2 slashes \\ or //
To handle this this case, we use rtrim to clear slashes.
Also, another use of dirname is to get virtual directory (url path), the issue is the same as above, we have to check and process before concatenating strings
bobray at softville dot com ¶
4 years ago
Be aware that if you call dirname(__FILE__) on Windows, you may get backslashes. If you then try to use str_replace() or preg_replace() to replace part of the path using forward slashes in your search pattern, there will be no match. You can normalize paths with $path = str_replace('\\', '/' ,$path) before doing any transformations
hans111 at yahoo dot com ¶
16 years ago
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.
soywiz at hotmail dot com ¶
19 years ago
You can use it to get parent directory:
include(dirname(__FILE__) . '/path/relative/file_to_include.php');
frederikreiss at gmx dot de ¶
9 years ago
what about a recursive dirname. To get $count levels up in a directory.
Xedecimal at gmail dot com ¶
16 years ago
Getting absolute path of the current script:
If anyone has a better way, get to the constructive critisism!
15 years ago
legolas558 dot sourceforge comma net ¶
16 years ago
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.
rudecoder at yahoo dot com ¶
20 years ago
Using this method on a file such as:
Now $base_url can be used in your HTML to reference other scripts in the same directory.
minimalist at intelligence dot com ¶
11 years ago
If you want to get the parent parent directory of your script, you can use this:
webyazilimci84 at gmail dot com ¶
13 years ago
BASE_PATH is for server side inclusions.
BASE_URL is for client side inclusions (scripts, css files, images etc.)
subzey at immelman dot ru ¶
12 years ago
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 "-фокус".
Quickfix is
str_replace("!$!", "", dirname(str_replace("/", "!$!/!$!", $q)))
Zingus J. Rinkle ¶
15 years ago
Most mkpath() function I saw listed here seem long and convoluted.
Here's mine:
ken dot forslund at hp dot com ¶
14 years ago
A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.
A solution to that, is to prefix all include paths with:
this will generate a base path relative to the current file, which will then allow an include behavior similar to C/C++.
thus, to include a file that is 1 in the parent directory:
to include a file that is in the same directory:
to include a file that is in a subdirectory:
Notice that all paths we reference must NOT begin with a /, and must be relative to the current file, in order to concatenate correctly.
rmahase at gmail dot com ¶
15 years ago
this little function gets the top level public directory
Yousef Ismaeil Cliprz ¶
10 years ago
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.
Holger Th?lking ¶
18 years ago
);
};
break;
}
} while (
dave at corecomm dot us ¶
20 years ago
Note that in both cases (root-folder script and non-root-folder script), BASE_PATH will include a trailing slash. At least with Apache on Darwin (Mac OS X), you can include(BASE_PATH.'/myfile.php'); and the doubled slash won't cause any problems, giving the same result as include(BASE_PATH.'myfile.php'); .
andrey at php dot net ¶
20 years ago
Code for write permissions check:
qeremy (!) gmail ¶
7 years ago
After PHP 7;
Before PHP 7;
);
}
return
renich at woralelandia dot com ¶
17 years ago
A nice "current directory" function.
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.
(PHP 4, PHP 5, PHP 7, PHP 8)
— Возвращает имя родительского каталога из указанного пути
Описание
(, $levels):
Функция наивно оперирует исключительно
исходной строкой и не учитывает реальную файловую систему
или компоненты пути типа «..«.
В Windows предполагает текущую установленную
кодовую страницу, поэтому для того, чтобы видеть правильное имя каталога
с путями многобайтовых символов, необходимо установить соответствующую кодовую страницу.
Если path содержит символы, недопустимые для текущей
кодовой страницы, поведение не определено.
В других системах предполагает, что path
закодирован в кодировке, совместимой с ASCII. В противном случае поведение функции не определено.
Список параметров
-
path На платформах Windows в качестве разделителей имён директорий
используются оба слеша (прямой/и обратный
\). В других операционных системах разделителем
служит прямой слеш (/).-
levels На сколько уровней вложенности вверх необходимо пройти.
Должно быть целым числом больше 0.
Возвращаемые значения
Возвращает путь к родительской директории. Если в параметре
path не содержится слешей, будет возвращена
точка (‘.‘), обозначающая текущую директорию.
В другом случае будет возвращён path
без последнего компонента /component.
Будьте осторожны при использовании этой функции в цикле,
который может достичь каталога верхнего уровня, так как это может привести к бесконечному циклу.
// Вернёт '.'.
// Вернёт `\` в Windows и '/' в *nix системах.
// Вернёт `\` в Windows и '.' в *nix системах.
// Вернёт 'C:\' в Windows и '.' в *nix системах.
Список изменений
Примеры
Пример #1 Пример использования функции
Результатом выполнения данного примера
будет что-то подобное:
/etc / (или \ в Windows) . C:\ /usr
Смотрите также
y dot a dot dejong at singular dot of dot alumni dot utwente dot nl ¶
8 years ago
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
tobylewis at mac dot com ¶
18 years ago
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.
tapken at engter dot de ¶
21 years ago
To get the directory of current included 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:
joe dot naylor at gmail dot com ¶
14 years ago
However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'. If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php.
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:
klugg this-is-junk at tlen dot pl ¶
17 years ago
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache:
ts at dev dot websafe dot pl ¶
15 years ago
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:
14 years ago
nhl261 at yahoo dot com ¶
12 years ago
As usual, to include or require a file, we use this
in rare case, we have current file existing at the root directory, dirname would return C:\ or / , then the line above contains 2 slashes \\ or //
To handle this this case, we use rtrim to clear slashes.
Also, another use of dirname is to get virtual directory (url path), the issue is the same as above, we have to check and process before concatenating strings
bobray at softville dot com ¶
4 years ago
Be aware that if you call dirname(__FILE__) on Windows, you may get backslashes. If you then try to use str_replace() or preg_replace() to replace part of the path using forward slashes in your search pattern, there will be no match. You can normalize paths with $path = str_replace('\\', '/' ,$path) before doing any transformations
hans111 at yahoo dot com ¶
16 years ago
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.
soywiz at hotmail dot com ¶
19 years ago
You can use it to get parent directory:
include(dirname(__FILE__) . '/path/relative/file_to_include.php');
frederikreiss at gmx dot de ¶
9 years ago
what about a recursive dirname. To get $count levels up in a directory.
Xedecimal at gmail dot com ¶
16 years ago
Getting absolute path of the current script:
If anyone has a better way, get to the constructive critisism!
15 years ago
legolas558 dot sourceforge comma net ¶
16 years ago
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.
rudecoder at yahoo dot com ¶
20 years ago
Using this method on a file such as:
Now $base_url can be used in your HTML to reference other scripts in the same directory.
minimalist at intelligence dot com ¶
11 years ago
If you want to get the parent parent directory of your script, you can use this:
webyazilimci84 at gmail dot com ¶
13 years ago
BASE_PATH is for server side inclusions.
BASE_URL is for client side inclusions (scripts, css files, images etc.)
subzey at immelman dot ru ¶
12 years ago
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 "-фокус".
Quickfix is
str_replace("!$!", "", dirname(str_replace("/", "!$!/!$!", $q)))
Zingus J. Rinkle ¶
15 years ago
Most mkpath() function I saw listed here seem long and convoluted.
Here's mine:
ken dot forslund at hp dot com ¶
14 years ago
A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.
A solution to that, is to prefix all include paths with:
this will generate a base path relative to the current file, which will then allow an include behavior similar to C/C++.
thus, to include a file that is 1 in the parent directory:
to include a file that is in the same directory:
to include a file that is in a subdirectory:
Notice that all paths we reference must NOT begin with a /, and must be relative to the current file, in order to concatenate correctly.
rmahase at gmail dot com ¶
15 years ago
this little function gets the top level public directory
Yousef Ismaeil Cliprz ¶
10 years ago
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.
Holger Th?lking ¶
18 years ago
);
};
break;
}
} while (
dave at corecomm dot us ¶
20 years ago
Note that in both cases (root-folder script and non-root-folder script), BASE_PATH will include a trailing slash. At least with Apache on Darwin (Mac OS X), you can include(BASE_PATH.'/myfile.php'); and the doubled slash won't cause any problems, giving the same result as include(BASE_PATH.'myfile.php'); .
andrey at php dot net ¶
20 years ago
Code for write permissions check:
qeremy (!) gmail ¶
7 years ago
After PHP 7;
Before PHP 7;
);
}
return
renich at woralelandia dot com ¶
17 years ago
A nice "current directory" function.
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.
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
— Информация о сервере и среде исполнения
Описание
Переменная $_SERVER — это массив (), содержащий такую информацию,
как заголовки, пути и местоположения скриптов.
Записи в этом массиве создаются веб-сервером, поэтому нет гарантии, что каждый веб-сервер будет
предоставлять любую из этих переменных; серверы могут опускать некоторые из них или предоставлять другие,
не указанные здесь.
Однако большинство из этих переменных учтены в спецификации
» CGI/1.1 и, скорее всего, будут определены.
Замечание:
При запуске PHP в командной строке
большинство из этих записей будут недоступны или не будут иметь никакого значения.
Индексы
- ‘PHP_SELF‘
Если PHP запущен в командной строке, эта переменная содержит
имя скрипта.
- ‘argv‘
Массив аргументов, переданных скрипту. Когда скрипт
запущен в командой строке, это даёт C-подобный доступ
к параметрам командной строки. Когда вызывается через метод GET,
этот массив будет содержать строку запроса.
- ‘argc‘
Содержит количество параметров, переданных скрипту
(если запуск произведён в командной строке).
- ‘GATEWAY_INTERFACE‘
Содержит используемую сервером версию спецификации CGI;
к примеру'CGI/1.1'..
- ‘SERVER_ADDR‘
- ‘SERVER_NAME‘
Имя хоста, на котором выполняется текущий скрипт.
Если скрипт выполняется на виртуальном хосте,
здесь будет содержатся имя, определённое для этого виртуального хоста.
Замечание:
В Apache 2 необходимо установитьUseCanonicalName = Onи
ServerName.
В противном случае это значение отразит имя хоста, предоставленное
клиентом, которое может быть подделано.
Небезопасно полагаться на это значение в контексте, требующем безопасности.
- ‘SERVER_SOFTWARE‘
Строка идентификации сервера, указанная в заголовках,
когда происходит ответ на запрос.
- ‘SERVER_PROTOCOL‘
Имя и версия информационного протокола, через который
была запрошена страница; к примеру'HTTP/1.0';
- ‘REQUEST_METHOD‘
Какой метод был использован для запроса страницы; к примеру'GET',
'HEAD','POST','PUT'.
PHP-скрипт завершается после отправки заголовков (то есть после того, как
осуществляется любой вывод без буферизации вывода), если метод запроса был
HEAD.- ‘REQUEST_TIME‘
Временная метка начала запроса.
- ‘REQUEST_TIME_FLOAT‘
Временная метка начала запроса с точностью до микросекунд.
- ‘QUERY_STRING‘
Строка запроса, если есть, через которую была открыта страница.
- ‘DOCUMENT_ROOT‘
Директория корня документов, в которой выполняется текущий скрипт,
в точности та, которая указана в конфигурационном файле сервера.
- ‘HTTPS‘
Принимает непустое значение, если запрос был произведён через протокол HTTPS.
- ‘REMOTE_ADDR‘
- ‘REMOTE_HOST‘
Удалённый хост, с которого пользователь просматривает текущую
страницу. Обратный поиск DNS основан на значении переменной
REMOTE_ADDR.
- ‘REMOTE_PORT‘
Порт на удалённой машине, который используется для связи с сервером.
- ‘REMOTE_USER‘
- ‘REDIRECT_REMOTE_USER‘
Аутентифицированный пользователь, если запрос был перенаправлен изнутри.
- ‘SCRIPT_FILENAME‘
Абсолютный путь к исполняемому скрипту.
- ‘SERVER_ADMIN‘
Эта переменная получает своё значение (для Apache) из директивы
конфигурационного файла сервера. Если скрипт запущен на
виртуальном хосте, это будет значение,
определённое для данного виртуального хоста.
- ‘SERVER_PORT‘
Порт на компьютере сервера, используемый сервером для соединения.
Для установок по умолчанию, значение будет'80';
используя SSL, например, это значение будет таким, какое сконфигурировано
для соединений безопасного HTTP.
Замечание:
Чтобы получить физический (реальный) порт в Apache 2, необходимо
установитьUseCanonicalName = Onи
UseCanonicalPhysicalPort = On, иначе это значение
может быть подменено и не вернуть реальной значение физического порта.
Полагаться на это значение небезопасно в контексте приложений, требующих
усиленной безопасности.
- ‘SERVER_SIGNATURE‘
Строка, содержащая версию сервера и имя виртуального хоста, которые
добавляются к генерируемым сервером страницам, если включено.
- ‘PATH_TRANSLATED‘
Путь файловой системы (не document root) к текущему скрипту, после того как сервер выполнил отображение virtual-to-real.
Замечание:
Пользователи Apache 2 могут использовать директиву
AcceptPathInfo = Onв конфигурационном файле
httpd.conf для задания переменной PATH_INFO.
- ‘SCRIPT_NAME‘
Содержит путь к текущему исполняемому скрипту. Это полезно для страниц,
которые должны указывать на самих себя.
Константа __FILE__
содержит полный путь и имя текущего (то есть включённого) файла.
- ‘REQUEST_URI‘
URI, который был предоставлен для доступа к этой странице.
Например, ‘/index.html‘.
- ‘PHP_AUTH_DIGEST‘
При выполнении аутентификации HTTP Digest этой переменной присваивается
заголовок ‘Authorization’, отправленный клиентом (который затем следует
использовать для проведения соответствующей проверки).
- ‘PHP_AUTH_USER‘
При выполнении HTTP-аутентификации этой переменной присваивается
имя пользователя, предоставленное пользователем.
- ‘PHP_AUTH_PW‘
При выполнении HTTP-аутентификации этой переменной присваивается
пароль, предоставленный пользователем.
- ‘AUTH_TYPE‘
При выполнении HTTP-аутентификации этой переменной присваивается
тип аутентификации, который используется.
- ‘PATH_INFO‘
- ‘ORIG_PATH_INFO‘
Исходное значение переменной ‘PATH_INFO‘ перед
обработкой PHP.
Примеры
Пример #1 Пример использования $_SERVER
Результатом выполнения данного примера
будет что-то подобное:
Примечания
Это ‘суперглобальная’ или автоматическая глобальная переменная. Это просто означает, что она доступна во всех контекстах скрипта. Нет необходимости выполнять global $variable; для доступа к ней внутри метода или функции.
Vladimir Kornea ¶
14 years ago
1. All elements of the $_SERVER array whose keys begin with 'HTTP_' come from HTTP request headers and are not to be trusted.
2. All HTTP headers sent to the script are made available through the $_SERVER array, with names prefixed by 'HTTP_'.
vcoletti at tiscali dot it ¶
3 years ago
To list all the $_SERVER parameters, simply do:
No need to list all possible keys of the array.
pierstoval at example dot com ¶
6 years ago
As PHP $_SERVER var is populated with a lot of vars, I think it's important to say that it's also populated with environment vars.
For example, with a PHP script, we can have this:
Will show "Hello".
But, internally, PHP makes sure that "internal" keys in $_SERVER are not overriden, so you wouldn't be able to do something like this:
Will show something like 1492897785
However, a lot of vars are still vulnerable from environment injection.
Lord Mac ¶
13 years ago
MarkAgius at markagius dot co dot uk ¶
11 years ago
You have missed 'REDIRECT_STATUS'
Very useful if you point all your error pages to the same file.
File; .htaccess
# .htaccess file.
ErrorDocument 404 /error-msg.php
ErrorDocument 500 /error-msg.php
ErrorDocument 400 /error-msg.php
ErrorDocument 401 /error-msg.php
ErrorDocument 403 /error-msg.php
# End of file.
jonbarnett at gmail dot com ¶
14 years ago
It's worth noting that $_SERVER variables get created for any HTTP request headers, including those you might invent:
If the browser sends an HTTP request header of:
X-Debug-Custom: some string
Works in PHP5 on Apache with mod_php. Don't know if this is true from other environments.
chris at ocproducts dot com ¶
6 years ago
Data: __FILE__
Data type: String
Purpose: The absolute pathname of the running PHP file, including the filename.
Caveat: This is not the file called by the PHP processor, it's what is running. So if you are inside an include, it's the include.
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: Yes
Data: __DIR__
Data type: String
Purpose: The absolute pathname to the running PHP file, excluding the filename
Caveat: This is not the file called by the PHP processor, it's what is running. So if you are inside an include, it's the include.
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: Yes
Note that if something is not set it may be missing from $_SERVER, or it may be blank, so use PHP's 'empty' function for your test.
Note that if you call "php --info" on the command line then naturally some of these settings are going to be blank, as no PHP file is involved.
Richard York ¶
13 years ago
Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell.
krinklemail at gmail dot com ¶
10 years ago
Mark Simon ¶
3 years ago
$_SERVER has nearly everything you need to know about the current web page environment. Something which would have been handy is easy access to the protocol and the actual web root.
Stefano (info at sarchittu dot org) ¶
12 years ago
A way to get the absolute path of your page, independent from the site position (so works both on local machine and on server without setting anything) and from the server OS (works both on Unix systems and Windows systems).
The only parameter it requires is the folder in which you place this script
So, for istance, I'll place this into my SCRIPT folder, and I'll write SCRIPT word length in $conflen
14 years ago
Depending on what you want to do the content of this variable, put in On or Off.
steve at sc-fa dot com ¶
13 years ago
If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy.
ywarnier at beeznest dot org ¶
5 years ago
This happens, for example, when calling the page through a call to stream_context_create() with a HTTP header of 'request_fulluri' set to 1.
Apparently, request_fulluri is useful when using some proxy servers.
One quick (and improvable) way to detect it would be to compare the start of the REQUEST_URI with REQUEST_SCHEME:
chris at ocproducts dot com ¶
6 years ago
Note that if something is not set it may be missing from $_SERVER, or it may be blank, so use PHP's 'empty' function for your test.
chris at ocproducts dot com ¶
6 years ago
Data: $_GET
Data type: Array (map)
Purpose: Contains all GET parameters (i.e. a parsed URL query string).
Caveat: GET parameter names have to be compliant with PHP variable naming, e.g. dots are not allowed and get substituted.
Works on web mode: Yes
Works on CLI mode: No
10 years ago
jarrod at squarecrow dot com ¶
13 years ago
info at mtprod dot com ¶
14 years ago
lemonostif at gmail dot com ¶
3 years ago
sammyhacker at gmail dot com ¶
1 year ago
To put it simply, $_SERVER contains all the environment variables.
CGI works by an HTTP application server filling in all the required environment variables and invoking the PHP process. And these environment variables are stored under $_SERVER.
pomat at live dot it ¶
10 years ago
On windows $result might be something like
1) "C:/apache/htdocs/subdir/file.php"
2) "C:/apache/htdocs//subdir/file.php"
3) "C:\apache\htdocs/subdir/file.php"
4) "C:\apache\htdocs\/subdir/file.php"
All those strings are parsed as "C:\apache\htdocs\subdir\file.php" (have a try with 'cd').
centurianii at yahoo dot co dot uk ¶
6 years ago
Now your $_SERVER global contains among others:
'REQUEST_URI' => '/a/b?x=1&y=2', it retains the initial url after the host
'QUERY_STRING' => 'a/b&x=1&y=2', notice how php replaces '?' with '&'
'SCRIPT_NAME' => '/index.php', as it was intended to be.
mirko dot steiner at slashdevslashnull dot de ¶
13 years ago
Google Chrome 3.0.195.27 Windows xp
Florin C ¶
2 months ago
"The online path is: "
php at isnoop dot net ¶
13 years ago
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.
SetEnv varname "variable value"
14 years ago
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
picov at e-link dot it ¶
11 years ago
A simple function to detect if the current page address was rewritten by mod_rewrite:
pudding06 at gmail dot com ¶
14 years ago
1 year ago
4 years ago
This may be important if you're building a RESTful interfaces that will also use methods such as PATCH and DELETE.
Also important as a security risk as a possible point of injection. In the event of building something acting based on REQUEST_METHOD, it's recommended to put it in a switch statement.
wbeaumo1 at gmail dot com ¶
13 years ago
jit_chavan at yahoo dot com ¶
9 years ago
2962051004 at qq dot com ¶
5 years ago
cupy at email dot cz ¶
13 years ago
try this example:
------------->8------------------
cat ./script_name.php
#! /usr/bin/php
Johan Winge ¶
3 years ago
3 years ago
To expand a bit on the price you could pay for relying on 'HTTP_REFERER': several large news sites I read often have paywalls, with cookies in place so you can only read X articles before you must subscribe; if using Incognito, they count the number of times you accessed via the same IP; everything to get you to subscribe. However, in order to be appealing, any visit where the 'HTTP_REFERER' is Google News will give you the entire article. I'm sure it's a dilemma their webmasters have, but for now any time someone sends you a story on one of them, all you have to do is search for the title and click the result from Google News. Bottom line: never count on it.
PS (1): ofcourse i'm talking about a friend. I pay for content.
PS (2): after some debate, the RFC decided to keep 'HTTP_REFERER', although it's misspelled.
What is file system root?
The root file system is the top of the hierarchical file tree. It contains the files and directories critical for system operation, including the device directory and programs for booting the system.
The root directory, or root folder, describes the uppermost folder on a hard drive partition. If your business computer contains a single partition, this partition will be the “C” drive and contains many system files.
Where or how to find the document root when launching localhost
Your document root is configured in Apache (assuming you use PHP through Apache httpd server here).
Php build in server is not showing document root
the problem:
I try to set up the build in php test server whit the commanprompt i use the command
php -S localhost:4100
and it outputs this

but acording to wiki’s and so it shoud output this

note: this is a recreation
info:
i am running PHP 7.4.6 (cli) (built: May 12 2020 11:38:54) ( ZTS Visual C++ 2017 x64 )
and my php filles (where i unzipped it in the installation) is C:\static\php
—
thanks already julian
You are comparing Windows output instead of Linux output. If Your server service is available under localhost:4100 then everything is OK so far 🙂
Php: DIR and DOCUMENT_ROOT returning different paths, PHP is going to get your document root from the web server .. IE DocumentRoot «/var/www/html/» inside of your vHosts or config file .. –
What is root folder in HTML?
Root directory of a website
The root directory, also known as the document root, web root, or site root directory, is the publicly accessible base folder of a website. This folder contains the index file (index. php, index. html or default. html) and is often named public_html, htdocs, www or wwwroot.
PHP built in webserver and Document root folder
So I’m watching Laracasts videos and got confused on how he got the document to
Listen to a folder
on his desktop?

I’m using the terminal to call php -S localhost:8888
I figured it out, when you’re working with a
PHP server
through command line make sure in terminal you change directory CD into the folder and start the server within the terminal php -S localhost:whateveryoupick.
for everyone else like me who looking for fast answer here is command to start
php server
with specified folder listing
php -S localhost:2376 -t /var/www/tmp$ crontab -e
@reboot php -S localhost:2376 -t /var/www/tmpAs of PHP 5.4.0, the
cli sapi
provides a built-in web server.
What does it mean «In case the PHP file is outside the document root, The default php.ini file for the server (e.g. /path/to/default/ini/php.ini ) will always be scanned, no matter where
Как подняться к корню каталога с помощью php, заходя в каждую папку
Вот тут мы и добрались до ответа на основой вопрос: «Как подняться к корню каталога с помощью php?» Для этого достаточно знать, что в операционных системах типа *nix ссылкой на предыдущую папку служит .., а в php есть функция, позволяющая менять каталог chdir(). То есть, для перехода на каталог выше, нужно указать скрипту: chdir ( '..' ). В итоге получим такой скрипт, который поднимается к корню каталога файловой системы, последовательно заходя во все встречные родительские папки:
<?php
while ( getcwd() != '/' ) { echo getcwd() . "<br/>"; chdir ( '..' );
}
?>Для того, чтобы программа не пыталась выйти за пределы операционной системы в открытый космос (всё равно не получится), в цикле while нужно указать ограничение, что дальше корня / даже не пытаться заходить: getcwd() != '/'. Иначе будет бесконечный цикл и программа будет тупо биться в конечную папку, пытаясь выйти за её пределы.
В результате наш скрипт бодро откроет все папки (и даже сможет по ним полазить, если нужно) и выдаст список того, в каких директориях он побывал:
What is meant by root directory?
In a computer file system, and primarily used in the Unix and Unix-like operating systems, the root directory is the first or top-most directory in a hierarchy. It can be likened to the trunk of a tree, as the starting point where all branches originate from.
What is a root directory of a website?
The root directory of your website holds the content that loads when visitors type your domain name in a browser. For example, you need to put your index file in your website’s root directory for visitors to see your site. Website-related applications might also need to know your website’s root directory.
How can I get root URL in php?
- $root = (! …
- $parsedUrl = parse_url(‘http://localhost/some/folder/containing/something/here/or/there’); $root = $parsedUrl[‘scheme’] . …
- $url = ‘http://user:pass@localhost:80/some/folder/containing/something/here/or/there’; $parsedUrl = parse_url($url); $root = strstr($url, $parsedUrl[‘path’], true) . ‘/’;
How do I set the root directory?
While all file systems have a root directory, it may be labeled differently depending on the operating system. For example, in Windows, the default root directory is C:. On Unix systems and in OS X, the root directory is typically labeled simply / (a single forward slash).
Where is my php directory?
- Check PHP Install Path On Linux. The whereis command returns the executable file path. …
- Check PHP Install Path On Windows. …
- Check Current PHP Version. …
- Use phpinfo() Function To Get PHP Version & PHP Install Path.
Резюме
Таким образом, разместив короткую программу на php в любое место на сервере, можно попасть в любую родительскую директорию. Что с этим делать и как можно использовать, как-нибудь в другой раз.
Напоследок полный работающий код для тестирования и дописывания этого php-скрипта. Скрипт безобидный: ничего не дописывает и не меняет на сервере, так что его можно использовать в качестве заготовки для написания более осмысленной программы, выполняющей определённые действия. 😉
<?php
echo "Текущая папка: <b>" . getcwd() . "</b><br/><br/>";
echo '<pre>';
print_r( preg_split ( '/\//', getcwd() ) );
echo '</pre>';
while ( getcwd() != '/' ) { echo getcwd() . "<br/>"; chdir ( '..' );
}
echo "<br>\$_SERVER['DOCUMENT_ROOT'] = <b>" . $_SERVER['DOCUMENT_ROOT'] . "</b><br>";
echo "\$_SERVER['SCRIPT_FILENAME'] = <b>" . $_SERVER['SCRIPT_FILENAME'] . "</b>";
?>Заберите ссылку на статью к себе, чтобы потом легко её найти!
Раз уж досюда дочитали, то может может есть желание рассказать об этом месте своим друзьям, знакомым и просто мимо проходящим?
Не надо себя сдерживать! 😉
Как получить список папок ветки дерева каталога, в котором лежит php-скрипт
<?php
echo '<pre>';
print_r( preg_split ( '/\//', getcwd() ) );
echo '</pre>';
?>В итоге получим вывод этого массива, в котором будут содержаться все папки, встречающиеся по пути от файла до корня файловой системы:
Array ( [0] => [1] => var [2] => www [3] => mb4 [4] => data [5] => www [6] => mb4.ru [7] => templates [8] => protostar [9] => html [10] => layouts [11] => joomla [12] => html [13] => batch )






