Статья, в которой рассмотрим как в php получить путь до корня сайта. Кроме того познакомимся с тем, чем отличается абсолютный путь в PHP и HTML.
Корень (слэш) в HTML и PHP
PHP в отличие от HTML видит файловую систему глубже. В HTML корнем сайта является некоторая директория, которая определяется настройками веб-сервера. Т.е. это определённый каталог в файловой системе, начиная с которого размещаются документы (файлы) этого сайта.
Например, в HTML путь к изображению image1.jpg
, которое расположено в каталоге images
относительно корня сайта будет иметь следующий вид:
/images/image1.jpg
В php слэш (/
) обозначает корень файловой системы, а не корень сайта.
Т.е. такая запись в php будет означать, что файл image1.jpg
расположен в директории images
, которая находится в корне файловой системы.
/images/image1.jpg
Чтобы к этому файлу добраться из php необходимо будет проделать более длинный путь. Т.е. сначала добраться до корня сайта (некоторой директории), а потом от него до нужного файла.
Например, на хостинге (в зависимости от хостинга путь до корня сайта может отличаться) путь к файлу будет следующим:
/home/m/mysiteru/public_html/images/image1.jpg
Например, путь к файлу сайта, который работает на веб-сервере Apache (сборка Денвер) в операционной системе Windows будет следующим:
Z:/home/mysite.ru/www/images/image1.jpg
PHP — Корень сайта
Получить корневую папку сайта в скрипте php можно используя предопределённый (глобальный) массив $_SERVER
:
$_SERVER['DOCUMENT_ROOT']
Чтобы посмотреть путь к корневому каталогу достаточно создать любой php файл и поместить в него следующее содержимое:
<?php
// вывести корень сайта
echo $_SERVER['DOCUMENT_ROOT'];
Абсолютный путь обычно применяют тогда, когда вы не знаете местоположение файлов относительно скрипта, в котором вы их используете.
Например, скопируем файл image1.jpg
, расположенный в корне сайта, в каталог images
(/assets/images
— путь от корня сайта):
<?php
// получить корень сайта
$root = $_SERVER['DOCUMENT_ROOT'];
//скопировать файл image1.png в папку images, расположенную в корне сайта
copy($root.'/image1.jpg', $root.'/assets/images/image1.jpg');
$_SERVER
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP
$_SERVER — Информация о сервере и среде исполнения
Описание
Переменная $_SERVER — это массив (array), содержащий такую информацию,
как заголовки, пути и местоположения скриптов.
Записи в этом массиве создаются веб-сервером, поэтому нет гарантии, что каждый веб-сервер будет
предоставлять любую из этих переменных; серверы могут опускать некоторые из них или предоставлять другие,
не указанные здесь.
Однако большинство из этих переменных учтены в спецификации
» CGI/1.1 и, скорее всего, будут определены.
Замечание:
При запуске PHP в командной строке
большинство из этих записей будут недоступны или не будут иметь никакого значения.
В дополнение к перечисленным ниже элементам, PHP будет создавать дополнительные элементы
со значениями из заголовков запросов. У элементов будет имя HTTP_
,
за которым следует имя заголовка, написанное с заглавной буквы и с подчёркиванием вместо дефиса.
Например, заголовок Accept-Language
будет доступен как $_SERVER['HTTP_ACCEPT_LANGUAGE']
.
Индексы
- ‘PHP_SELF‘
-
Имя файла скрипта, который сейчас выполняется, относительно
корня документов. Например, $_SERVER[‘PHP_SELF’] в скрипте
по адресу http://example.com/foo/bar.php
будет /foo/bar.php.
Константа __FILE__
содержит полный путь и имя файла текущего (то есть
подключённого) файла.
Если PHP запущен в командной строке, эта переменная содержит
имя скрипта.
- ‘argv’
-
Массив аргументов, переданных скрипту. Когда скрипт
запущен в командой строке, это даёт C-подобный доступ
к параметрам командной строки. Когда вызывается через метод GET,
этот массив будет содержать строку запроса.
- ‘argc’
-
Содержит количество параметров, переданных скрипту
(если запуск произведён в командной строке).
- ‘GATEWAY_INTERFACE‘
-
Содержит используемую сервером версию спецификации CGI;
к примеру'CGI/1.1'
..
- ‘SERVER_ADDR‘
-
IP-адрес сервера, на котором выполняется текущий скрипт.
- ‘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‘
-
IP-адрес, с которого пользователь просматривает текущую страницу.
- ‘REMOTE_HOST‘
-
Удалённый хост, с которого пользователь просматривает текущую
страницу. Обратный поиск DNS основан на значении переменной
REMOTE_ADDR.
Замечание:
Сервер должен быть настроен, чтобы создавать эту переменную.
Для примера, в Apache необходимо присутствие директивы
HostnameLookups On
в файле httpd.conf, чтобы эта
переменная создавалась. Смотрите также gethostbyaddr().
- ‘REMOTE_PORT‘
-
Порт на удалённой машине, который используется для связи с сервером.
- ‘REMOTE_USER‘
-
Аутентифицированный пользователь.
- ‘REDIRECT_REMOTE_USER‘
-
Аутентифицированный пользователь, если запрос был перенаправлен изнутри.
- ‘SCRIPT_FILENAME‘
-
Абсолютный путь к исполняемому скрипту.
Замечание:
Если скрипт запускается в командной строке (CLI), используя
относительный путь, такой как file.php или
../file.php, переменная
$_SERVER[‘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‘
-
Содержит любой предоставленный пользователем путь, содержащийся после
имени скрипта, но до строки запроса, если она есть.
Например, если текущий скрипт запрошен по URL
http://www.example.com/php/path_info.php/some/stuff?foo=bar,
то переменная $_SERVER[‘PATH_INFO’] будет содержать
/some/stuff
.
- ‘ORIG_PATH_INFO‘
-
Исходное значение переменной ‘PATH_INFO‘ перед
обработкой PHP.
Примеры
Пример #1 Пример использования $_SERVER
<?php
echo $_SERVER['SERVER_NAME'];
?>
Вывод приведённого примера будет похож на:
Примечания
Замечание:
Это «суперглобальная»,
или автоматическая глобальная, переменная. Это просто означает, что она доступна во всех контекстах скрипта.
Нет необходимости выполнять global $variable; для доступа к ней внутри метода или функции.
Нашли ошибку?
Vladimir Kornea ¶
16 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_'.
3. $_SERVER['PHP_SELF'] is dangerous if misused. If login.php/nearly_arbitrary_string is requested, $_SERVER['PHP_SELF'] will contain not just login.php, but the entire login.php/nearly_arbitrary_string. If you've printed $_SERVER['PHP_SELF'] as the value of the action attribute of your form tag without performing HTML encoding, an attacker can perform XSS attacks by offering users a link to your site such as this:
<a href='http://www.example.com/login.php/"><script type="text/javascript">...</script><span a="'>Example.com</a>
The javascript block would define an event handler function and bind it to the form's submit event. This event handler would load via an <img> tag an external file, with the submitted username and password as parameters.
Use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']. HTML encode every string sent to the browser that should not be interpreted as HTML, unless you are absolutely certain that it cannot contain anything that the browser can interpret as HTML.
vcoletti at tiscali dot it ¶
5 years ago
To list all the $_SERVER parameters, simply do:
foreach ($_SERVER as $parm => $value) echo "$parm = '$value'\n";
No need to list all possible keys of the array.
MarkAgius at markagius dot co dot uk ¶
13 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.
File; error-msg.php
<?php
$HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
if($HttpStatus==200) {print "Document has been processed and sent to you.";}
if($HttpStatus==400) {print "Bad HTTP request ";}
if($HttpStatus==401) {print "Unauthorized - Iinvalid password";}
if($HttpStatus==403) {print "Forbidden";}
if($HttpStatus==500) {print "Internal Server Error";}
if($HttpStatus==418) {print "I'm a teapot! - This is a real value, defined in 1998";}?>
Lord Mac ¶
15 years ago
An even *more* improved version...
<?php
phpinfo(32);
?>
pierstoval at example dot com ¶
8 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:
MY_ENV_VAR=Hello php -r 'echo $_SERVER["MY_ENV_VAR"];'
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:
REQUEST_TIME=Hello php -r 'var_dump($_SERVER["REQUEST_TIME"]);'
Will show something like 1492897785
However, a lot of vars are still vulnerable from environment injection.
I created a gist here ( https://gist.github.com/Pierstoval/f287d3e61252e791a943dd73874ab5ee ) with my PHP configuration on windows with PHP7.0.15 on WSL with bash, the results are that the only "safe" vars are the following:
PHP_SELF
SCRIPT_NAME
SCRIPT_FILENAME
PATH_TRANSLATED
DOCUMENT_ROOT
REQUEST_TIME_FLOAT
REQUEST_TIME
argv
argc
All the rest can be overriden with environment vars, which is not very cool actually because it can break PHP applications sometimes...
(and I only tested on CLI, I had no patience to test with Apache mod_php or Nginx + PHP-FPM, but I can imagine that not a lot of $_SERVER properties are "that" secure...)
jonbarnett at gmail dot com ¶
16 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
Then:
<?php
$_SERVER['HTTP_X_DEBUG_CUSTOM']; // "some string"
?>
There are better ways to identify the HTTP request headers sent by the browser, but this is convenient if you know what to expect from, for example, an AJAX script with custom headers.
Works in PHP5 on Apache with mod_php. Don't know if this is true from other environments.
chris at ocproducts dot com ¶
8 years ago
Guide to absolute paths...
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
Data: $_SERVER['SCRIPT_FILENAME']
Data type: String
Purpose: The absolute pathname of the origin PHP file, including the filename
Caveat: Not set on all PHP environments, may need setting by copying from __FILE__ before other files are included.
Caveat: Symbolic links are not pre-resolved, use PHP's 'realpath' function if you need it resolved.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Caveat: "Filename" makes you think it is just a filename, but it really is the full absolute pathname. Read the identifier as "Script's filesystem (path)name".
Works on web mode: Yes
Works on CLI mode: Yes
Data: $_SERVER['PATH_TRANSLATED']
Data type: String
Purpose: The absolute pathname of the origin PHP file, including the filename
Caveat: It's probably not set, best to just not use it. Just use realpath($_SERVER['SCRIPT_FILENAME']) (and be aware that itself may need to have been emulated).
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: No
Data: $_SERVER['DOCUMENT_ROOT']
Data type: String
Purpose: Get the absolute path to the web server's document root. No trailing slash.
Caveat: Don't trust this to be set, or set correctly, unless you control the server environment.
Caveat: May or may not have symbolic links pre-resolved, use PHP's 'realpath' function if you need it resolved.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: No
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.
ywarnier at beeznest dot org ¶
7 years ago
Note that $_SERVER['REQUEST_URI'] might include the scheme and domain in certain cases.
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.
For example:
$http = ['request_fulluri' => 1, /* other params here */];
$context = stream_context_create(array( 'http' => $http ));
$fp = fopen($some_url, 'rb', false, $context);
When outputting $_SERVER['REQUEST_URI'] on the server at $some_url, you will get
https://some_url/some_script.php
Remove the request_fulluri => 1 option, and $_SERVER['REQUEST_URI'] gets back to its "normal":
/some_script.php
Apparently, request_fulluri is useful when using some proxy servers.
In this case, there is no proper way to "detect" if this option was set or not, and you should probably use a combination of other $_SERVER[] elements (like REQUEST_SCHEME, SERVER_NAME and SERVER_PORT) to determine if this was the case.
One quick (and improvable) way to detect it would be to compare the start of the REQUEST_URI with REQUEST_SCHEME:
$scheme = $_SERVER['REQUEST_SCHEME'] . '://';
if (strcmp(substr($_SERVER['REQUEST_URI'], 0, strlen($scheme)), $scheme) === 0) {
// request_fulluri was set
}
Richard York ¶
15 years ago
Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell.
["_SERVER"]=>
array(24) {
["MANPATH"]=>
string(48) "/usr/share/man:/usr/local/share/man:/usr/X11/man"
["TERM"]=>
string(11) "xterm-color"
["SHELL"]=>
string(9) "/bin/bash"
["SSH_CLIENT"]=>
string(20) "127.0.0.1 41242 22"
["OLDPWD"]=>
string(60) "/Library/WebServer/Domains/www.example.com/private"
["SSH_TTY"]=>
string(12) "/dev/ttys000"
["USER"]=>
string(5) "username"
["MAIL"]=>
string(15) "/var/mail/username"
["PATH"]=>
string(57) "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin"
["PWD"]=>
string(56) "/Library/WebServer/Domains/www.example.com/www"
["SHLVL"]=>
string(1) "1"
["HOME"]=>
string(12) "/Users/username"
["LOGNAME"]=>
string(5) "username"
["SSH_CONNECTION"]=>
string(31) "127.0.0.1 41242 10.0.0.1 22"
["_"]=>
string(12) "/usr/bin/php"
["__CF_USER_TEXT_ENCODING"]=>
string(9) "0x1F5:0:0"
["PHP_SELF"]=>
string(10) "Shell.php"
["SCRIPT_NAME"]=>
string(10) "Shell.php"
["SCRIPT_FILENAME"]=>
string(10) "Shell.php"
["PATH_TRANSLATED"]=>
string(10) "Shell.php"
["DOCUMENT_ROOT"]=>
string(0) ""
["REQUEST_TIME"]=>
int(1247162183)
["argv"]=>
array(1) {
[0]=>
string(10) "Shell.php"
}
["argc"]=>
int(1)
}
krinklemail at gmail dot com ¶
12 years ago
If requests to your PHP script send a header "Content-Type" or/ "Content-Length" it will, contrary to regular HTTP headers, not appear in $_SERVER as $_SERVER['HTTP_CONTENT_TYPE']. PHP removes these (per CGI/1.1 specification[1]) from the HTTP_ match group.
They are still accessible, but only if the request was a POST request. When it is, it'll be available as:
$_SERVER['CONTENT_LENGTH']
$_SERVER['CONTENT_TYPE']
[1] https://www.ietf.org/rfc/rfc3875
chris at ocproducts dot com ¶
8 years ago
Guide to URL paths...
Data: $_SERVER['PHP_SELF']
Data type: String
Purpose: The URL path name of the current PHP file, including path-info (see $_SERVER['PATH_INFO']) and excluding URL query string. Includes leading slash.
Caveat: This is after URL rewrites (i.e. it's as seen by PHP, not necessarily the original call URL).
Works on web mode: Yes
Works on CLI mode: Tenuous (emulated to contain just the exact call path of the CLI script, with whatever exotic relative pathname you may call with, not made absolute and not normalised or pre-resolved)
Data: $_SERVER['SCRIPT_NAME']
Data type: String
Purpose: The URL path name of the current PHP file, excluding path-info and excluding URL query string. Includes leading slash.
Caveat: This is after URL rewrites (i.e. it's as seen by PHP, not necessarily the original call URL).
Caveat: Not set on all PHP environments, may need setting via preg_replace('#\.php/.*#', '.php', $_SERVER['PHP_SELF']).
Works on web mode: Yes
Works on CLI mode: Tenuous (emulated to contain just the exact call path of the CLI script, with whatever exotic relative pathname you may call with, not made absolute and not normalised or pre-resolved)
Data: $_SERVER['REDIRECT_URL']
Data type: String
Purpose: The URL path name of the current PHP file, path-info is N/A and excluding URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL).
Caveat: Not set on all PHP environments, and definitely only ones with URL rewrites.
Works on web mode: Yes
Works on CLI mode: No
Data: $_SERVER['REQUEST_URI']
Data type: String
Purpose: The URL path name of the current PHP file, including path-info and including URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL). *
*: I've seen at least one situation where this is not true (there was another $_SERVER variable to use instead supplied by the URL rewriter), but the author of the URL rewriter later fixed it so probably fair to dismiss this particular note.
Caveat: Not set on all PHP environments, may need setting via $_SERVER['REDIRECT_URL'] . '?' . http_build_query($_GET) [if $_SERVER['REDIRECT_URL'] is set, and imperfect as we don't know what GET parameters were originally passed vs which were injected in the URL rewrite] --otherwise-- $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET).
Works on web mode: Yes
Works on CLI mode: No
Data: $_SERVER['PATH_INFO']
Data type: String
Purpose: Find the path-info, which is data after the .php filename in the URL call. It's a strange concept.
Caveat: Some environments may not support it, it is best avoided unless you have complete server control
Works on web mode: Yes
Works on CLI mode: No
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.
lemonostif at gmail dot com ¶
5 years ago
PHP_SELF is a disgrace of a programmer's work. One of the most widespread PHP vulnerabilities since version 4 and the manual says nothing about the dangers. At least clarify that ITS VALUE CAN BE PROVIDED BY THE USER with capitals preferably if you want to make the internet a safer place...
Daniels118 ¶
3 years ago
If you need to know the protocol (http or https) used by the client, then the $_SERVER['HTTPS'] variable may not actually report the truth if your server is behind a proxy or a load balancer (In fact the client could connect to the load balancer using https, and then the load balancer forward the request to the server using http).
If the proxy/load balancer is correctly configured it could send the original request protocol in a header, and you will find it in the $_SERVER[HTTP_X_FORWARDED_PROTO] variable.
Mark Simon ¶
5 years ago
So near, and yet so far …
$_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.
For the protocol, you may or may not have $_SERVER['HTTPS'] and it may or may not be empty. For the web root, $_SERVER['DOCUMENT_ROOT'] depends on the server configuration, and doesn’t work for virtual hosts.
For practical purposes, I normally include something like the following in my scripts:
<?php
// Web Root
// Usage: include("$root/includes/something.inc.php");
$root = $_SERVER['WEB_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'],'',$_SERVER['SCRIPT_FILENAME']);// Host & Protocol
// Usage: $url = "$protocol://$host/images/something.jpg";
$host = $_SERVER['HTTP_HOST'];
$protocol=$_SERVER['PROTOCOL'] = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http';
?>
Tonin ¶
16 years ago
When using the $_SERVER['SERVER_NAME'] variable in an apache virtual host setup with a ServerAlias directive, be sure to check the UseCanonicalName apache directive. If it is On, this variable will always have the apache ServerName value. If it is Off, it will have the value given by the headers sent by the browser.
Depending on what you want to do the content of this variable, put in On or Off.
Stefano (info at sarchittu dot org) ¶
14 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
<?php
$conflen=strlen('SCRIPT');
$B=substr(__FILE__,0,strrpos(__FILE__,'/'));
$A=substr($_SERVER['DOCUMENT_ROOT'], strrpos($_SERVER['DOCUMENT_ROOT'], $_SERVER['PHP_SELF']));
$C=substr($B,strlen($A));
$posconf=strlen($C)-$conflen-1;
$D=substr($C,1,$posconf);
$host='http://'.$_SERVER['SERVER_NAME'].'/'.$D;
?>
$host will finally contain the absolute path.
info at mtprod dot com ¶
16 years ago
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
steve at sc-fa dot com ¶
15 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.
$_SERVER['HTTP_X_FORWARDED_FOR'] in place of $_SERVER['REMOTE_ADDR']
$_SERVER['HTTP_X_FORWARDED_HOST'] and
$_SERVER['HTTP_X_FORWARDED_SERVER'] in place of (at least in our case,) $_SERVER['SERVER_NAME']
jarrod at squarecrow dot com ¶
15 years ago
$_SERVER['DOCUMENT_ROOT'] is incredibly useful especially when working in your development environment. If you're working on large projects you'll likely be including a large number of files into your pages. For example:
<?php
//Defines constants to use for "include" URLS - helps keep our paths clean
define("REGISTRY_CLASSES", $_SERVER['DOCUMENT_ROOT']."/SOAP/classes/");
define("REGISTRY_CONTROLS", $_SERVER['DOCUMENT_ROOT']."/SOAP/controls/");
define("STRING_BUILDER", REGISTRY_CLASSES. "stringbuilder.php");
define("SESSION_MANAGER", REGISTRY_CLASSES. "sessionmanager.php");
define("STANDARD_CONTROLS", REGISTRY_CONTROLS."standardcontrols.php");
?>
In development environments, you're rarely working with your root folder, especially if you're running PHP locally on your box and using DOCUMENT_ROOT is a great way to maintain URL conformity. This will save you hours of work preparing your application for deployment from your box to a production server (not to mention save you the headache of include path failures).
pomat at live dot it ¶
11 years ago
$_SERVER['DOCUMENT_ROOT'] may contain backslashes on windows systems, and of course it may or may not have a trailing slash (backslash).
I saw the following as an example of the proper way we're supposed to deal with this issue:
<?php
include(dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR . 'file.php');
?>
Ok, the latter may be used to access a file inside the parent directory of the document root, but actually does not properly address the issue.
In the end, don't warry about. It should be safe to use forward slashes and append a trailing slash in all cases.
Let's say we have this:
<?php
$path = 'subdir/file.php';
$result = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
?>
On linux $result might be something like
1) "/var/www/subdir/file.php"
2) "/var/www//subdir/file.php"
String 2 is parsed the same as string 1 (have a try with command 'cd').
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').
Tom ¶
12 years ago
Be warned that most contents of the Server-Array (even $_SERVER['SERVER_NAME']) are provided by the client and can be manipulated. They can also be used for injections and thus MUST be checked and treated like any other user input.
chris ¶
15 years ago
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
pudding06 at gmail dot com ¶
16 years ago
Here's a simple, quick but effective way to block unwanted external visitors to your local server:
<?php
// only local requests
if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') die(header("Location: /"));
?>
This will direct all external traffic to your home page. Of course you could send a 404 or other custom error. Best practice is not to stay on the page with a custom error message as you acknowledge that the page does exist. That's why I redirect unwanted calls to (for example) phpmyadmin.
picov at e-link dot it ¶
13 years ago
A simple function to detect if the current page address was rewritten by mod_rewrite:
<?php
public function urlWasRewritten() {
$realScriptName=$_SERVER['SCRIPT_NAME'];
$virtualScriptName=reset(explode("?", $_SERVER['REQUEST_URI']));
return !($realScriptName==$virtualScriptName);
}
?>
lilJoshu ¶
6 years ago
Remember,
Although $_SERVER["REQUEST_METHOD"] is initially built with GET, POST, PUT, HEAD in mind, a server can allow more.
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.
<?php
switch ($_SERVER["REQUEST_METHOD"]){
case "PUT":
foo_replace_data();
break;
case "POST":
foo_add_data();
break;
case "HEAD";
foo_set_that_cookie();
break;
case "GET":
default:
foo_fetch_stuff()
break;
}?>
centurianii at yahoo dot co dot uk ¶
7 years ago
If you apply redirection in ALL your requests using commands at the Apache virtual host file like:
RewriteEngine On
RewriteCond "%{REQUEST_URI}" "!=/index.php"
RewriteRule "^/(.*)$" "index.php?$1" [NC,NE,L,QSA]
you should expect some deviations in your $_SERVER global.
Say, you send a url of: [hostname here]/a/b?x=1&y=2
which makes Apache to modify to: /index.php?/a/b?x=1&y=2
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.
To test your $_SERVER global:
function serverArray(){
$arr = array();
foreach($_SERVER as $key=>$value)
$arr[] = ' \'' . $key . '\' => \'' . (isset($value)? $value : '-') . '\'';
return @\sort($arr)? '$_SERVER = array(<br />' . implode($arr, ',<br />') . '<br />);' : false;
}
echo serverArray();
mirko dot steiner at slashdevslashnull dot de ¶
15 years ago
<?php// RFC 2616 compatible Accept Language Parser
// http://www.ietf.org/rfc/rfc2616.txt, 14.4 Accept-Language, Page 104
// Hypertext Transfer Protocol -- HTTP/1.1foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
$pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})'.
'(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)'.
'(?P<quantifier>\d\.\d))?$/';$splits = array();printf("Lang:,,%s''\n", $lang);
if (preg_match($pattern, $lang, $splits)) {
print_r($splits);
} else {
echo "\nno match\n";
}
}?>
example output:
Google Chrome 3.0.195.27 Windows xp
Lang:,,de-DE''
Array
(
[0] => de-DE
[primarytag] => de
[1] => de
[subtag] => DE
[2] => DE
)
Lang:,,de;q=0.8''
Array
(
[0] => de;q=0.8
[primarytag] => de
[1] => de
[subtag] =>
[2] =>
[quantifier] => 0.8
[3] => 0.8
)
Lang:,,en-US;q=0.6''
Array
(
[0] => en-US;q=0.6
[primarytag] => en
[1] => en
[subtag] => US
[2] => US
[quantifier] => 0.6
[3] => 0.6
)
Lang:,,en;q=0.4''
Array
(
[0] => en;q=0.4
[primarytag] => en
[1] => en
[subtag] =>
[2] =>
[quantifier] => 0.4
[3] => 0.4
)
kamil00110 ¶
1 year ago
This code can be used to help find somone that tries to dig throught the server files to find something.
.htaccess
ErrorDocument 404 /your.php
ErrorDocument 403 /your.php
<?php
//get time
$time = date("H:i:s d.m.y");
//get user address
$usr = $_SERVER['REMOTE_ADDR'];
//get entered url of the "visitor"
$url = $_SERVER['REQUEST_URI'];
//get your servers address
$ip = $_SERVER['SERVER_ADDR'];
//put toogether
$sus = "[".$time."] ".$usr." ".$ip.$url.PHP_EOL;
//write an log file
file_put_contents("susip.txt", $sus, FILE_APPEND);
?>
php at isnoop dot net ¶
15 years ago
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.
SetEnv varname "variable value"
sammyhacker at gmail dot com ¶
3 years 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.
jit_chavan at yahoo dot com ¶
11 years ago
searched $_SERVER["REDIRECT_URL"] for a while and noted that it is not mentioned in php documentation page itself. look like this is only generated by apache server(not others) and using $_SERVER["REQUEST_URI"] will be useful in some cases as mine.
chris at ocproducts dot com ¶
8 years ago
Guide to script parameters...
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
Data: $_SERVER['QUERY_STRING']
Data type: String
Purpose: Gets an unparsed URL query string.
Caveat: Not set on all PHP environments, may need setting via http_build_query($_GET).
Works on web mode: Yes
Works on CLI mode: No
Data: $_SERVER['argv']
Data type: Array (list)
Purpose: Get CLI call parameters.
Works on web mode: Tenuous (just contains a single parameter, the query string)
Works on CLI mode: Yes
wbeaumo1 at gmail dot com ¶
14 years ago
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
2962051004 at qq dot com ¶
7 years ago
<?php
/*
Sometimes you will find that your website will not get the correct user IP after adding CDN, then this function will help you
*/
function real_ip()
{
$ip = $_SERVER['REMOTE_ADDR'];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
foreach ($matches[0] AS $xip) {
if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
$ip = $xip;
break;
}
}
} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
$ip = $_SERVER['HTTP_X_REAL_IP'];
}
return $ip;
}
echo
real_ip();?>
Johan Winge ¶
5 years ago
It should probably be noted that the value of $_SERVER['SERVER_PROTOCOL'] will never contain the substring "HTTPS". Assuming this is a common source of bugs and confusion. Instead, see $_SERVER['HTTPS'].
- September 9, 2022
- PHP
- Refer to website root in PHP (Windows)
- PHP absolute path to root
- Finding the PHP Document Root
- PHP Include from Root
- Root path doesn’t work with php include
- What is Web Root
- Keeping files above web root/directory
Refer to website root in PHP (Windows)
$_SERVER['DOCUMENT_ROOT']
$root = realpath(dirname(__FILE__) . '/../../..');
PHP absolute path to root
localhost/MySite
-->Admin
-- Edit.php
-->Class
-- class.EditInfo.php
-->Texts
-- MyInfo.txt
--ShowInfo.php
define('ROOTPATH', __DIR__);
define('ROOTPATH', dirname(__FILE__));
if (file_exists(ROOTPATH.'/Texts/MyInfo.txt')) {
// ...
}
if (file_exists($_SERVER['DOCUMENT_ROOT'].'/Texts/MyInfo.txt')) {
// ...
}
$_SERVER['DOCUMENT_ROOT']
define("LOCAL_PATH_ROOT", $_SERVER["DOCUMENT_ROOT"]);
define("HTTP_PATH_ROOT", isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : (isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : '_UNKNOWN_'));
str_replace(LOCAL_PATH_ROOT, RELATIVE_PATH_ROOT, $my_path)
str_replace(LOCAL_PATH_ROOT, RELATIVE_PATH_ROOT, str_replace(DIRECTORY_SEPARATOR, '/', $my_path))
defined('LOCAL_PATH_BOOTSTRAP') || define("LOCAL_PATH_BOOTSTRAP", __DIR__);
// -----------------------------------------------------------------------
// DEFINE SEPERATOR ALIASES
// -----------------------------------------------------------------------
define("URL_SEPARATOR", '/');
define("DS", DIRECTORY_SEPARATOR);
define("PS", PATH_SEPARATOR);
define("US", URL_SEPARATOR);
// -----------------------------------------------------------------------
// DEFINE ROOT PATHS
// -----------------------------------------------------------------------
define("RELATIVE_PATH_ROOT", '');
define("LOCAL_PATH_ROOT", $_SERVER["DOCUMENT_ROOT"]);
define("HTTP_PATH_ROOT",
isset($_SERVER["HTTP_HOST"]) ?
$_SERVER["HTTP_HOST"] : (
isset($_SERVER["SERVER_NAME"]) ?
$_SERVER["SERVER_NAME"] : '_UNKNOWN_'));
// -----------------------------------------------------------------------
// DEFINE RELATIVE PATHS
// -----------------------------------------------------------------------
define("RELATIVE_PATH_BASE",
str_replace(LOCAL_PATH_ROOT, RELATIVE_PATH_ROOT, getcwd()));
define("RELATIVE_PATH_APP", dirname(RELATIVE_PATH_BASE));
define("RELATIVE_PATH_LIBRARY", RELATIVE_PATH_APP . DS . 'vendor');
define("RELATIVE_PATH_HELPERS", RELATIVE_PATH_BASE);
define("RELATIVE_PATH_TEMPLATE", RELATIVE_PATH_BASE . DS . 'templates');
define("RELATIVE_PATH_CONFIG", RELATIVE_PATH_BASE . DS . 'config');
define("RELATIVE_PATH_PAGES", RELATIVE_PATH_BASE . DS . 'pages');
define("RELATIVE_PATH_ASSET", RELATIVE_PATH_BASE . DS . 'assets');
define("RELATIVE_PATH_ASSET_IMG", RELATIVE_PATH_ASSET . DS . 'img');
define("RELATIVE_PATH_ASSET_CSS", RELATIVE_PATH_ASSET . DS . 'css');
define("RELATIVE_PATH_ASSET_JS", RELATIVE_PATH_ASSET . DS . 'js');
// -----------------------------------------------------------------------
// DEFINE LOCAL PATHS
// -----------------------------------------------------------------------
define("LOCAL_PATH_BASE", LOCAL_PATH_ROOT . RELATIVE_PATH_BASE);
define("LOCAL_PATH_APP", LOCAL_PATH_ROOT . RELATIVE_PATH_APP);
define("LOCAL_PATH_LIBRARY", LOCAL_PATH_ROOT . RELATIVE_PATH_LIBRARY);
define("LOCAL_PATH_HELPERS", LOCAL_PATH_ROOT . RELATIVE_PATH_HELPERS);
define("LOCAL_PATH_TEMPLATE", LOCAL_PATH_ROOT . RELATIVE_PATH_TEMPLATE);
define("LOCAL_PATH_CONFIG", LOCAL_PATH_ROOT . RELATIVE_PATH_CONFIG);
define("LOCAL_PATH_PAGES", LOCAL_PATH_ROOT . RELATIVE_PATH_PAGES);
define("LOCAL_PATH_ASSET", LOCAL_PATH_ROOT . RELATIVE_PATH_ASSET);
define("LOCAL_PATH_ASSET_IMG", LOCAL_PATH_ROOT . RELATIVE_PATH_ASSET_IMG);
define("LOCAL_PATH_ASSET_CSS", LOCAL_PATH_ROOT . RELATIVE_PATH_ASSET_CSS);
define("LOCAL_PATH_ASSET_JS", LOCAL_PATH_ROOT . RELATIVE_PATH_ASSET_JS);
// -----------------------------------------------------------------------
// DEFINE URL PATHS
// -----------------------------------------------------------------------
if (US === DS) { // needed for compatibility with windows
define("HTTP_PATH_BASE", HTTP_PATH_ROOT . RELATIVE_PATH_BASE);
define("HTTP_PATH_APP", HTTP_PATH_ROOT . RELATIVE_PATH_APP);
define("HTTP_PATH_LIBRARY", false);
define("HTTP_PATH_HELPERS", false);
define("HTTP_PATH_TEMPLATE", false);
define("HTTP_PATH_CONFIG", false);
define("HTTP_PATH_PAGES", false);
define("HTTP_PATH_ASSET", HTTP_PATH_ROOT . RELATIVE_PATH_ASSET);
define("HTTP_PATH_ASSET_IMG", HTTP_PATH_ROOT . RELATIVE_PATH_ASSET_IMG);
define("HTTP_PATH_ASSET_CSS", HTTP_PATH_ROOT . RELATIVE_PATH_ASSET_CSS);
define("HTTP_PATH_ASSET_JS", HTTP_PATH_ROOT . RELATIVE_PATH_ASSET_JS);
} else {
define("HTTP_PATH_BASE", HTTP_PATH_ROOT .
str_replace(DS, US, RELATIVE_PATH_BASE));
define("HTTP_PATH_APP", HTTP_PATH_ROOT .
str_replace(DS, US, RELATIVE_PATH_APP));
define("HTTP_PATH_LIBRARY", false);
define("HTTP_PATH_HELPERS", false);
define("HTTP_PATH_TEMPLATE", false);
define("HTTP_PATH_CONFIG", false);
define("HTTP_PATH_PAGES", false);
define("HTTP_PATH_ASSET", HTTP_PATH_ROOT .
str_replace(DS, US, RELATIVE_PATH_ASSET));
define("HTTP_PATH_ASSET_IMG", HTTP_PATH_ROOT .
str_replace(DS, US, RELATIVE_PATH_ASSET_IMG));
define("HTTP_PATH_ASSET_CSS", HTTP_PATH_ROOT .
str_replace(DS, US, RELATIVE_PATH_ASSET_CSS));
define("HTTP_PATH_ASSET_JS", HTTP_PATH_ROOT .
str_replace(DS, US, RELATIVE_PATH_ASSET_JS));
}
// -----------------------------------------------------------------------
// DEFINE REQUEST PARAMETERS
// -----------------------------------------------------------------------
define("REQUEST_QUERY",
isset($_SERVER["QUERY_STRING"]) && $_SERVER["QUERY_STRING"] != '' ?
$_SERVER["QUERY_STRING"] : false);
define("REQUEST_METHOD",
isset($_SERVER["REQUEST_METHOD"]) ?
strtoupper($_SERVER["REQUEST_METHOD"]) : false);
define("REQUEST_STATUS",
isset($_SERVER["REDIRECT_STATUS"]) ?
$_SERVER["REDIRECT_STATUS"] : false);
define("REQUEST_PROTOCOL",
isset($_SERVER["HTTP_ORIGIN"]) ?
substr($_SERVER["HTTP_ORIGIN"], 0,
strpos($_SERVER["HTTP_ORIGIN"], '://') + 3) : 'http://');
define("REQUEST_PATH",
isset($_SERVER["REQUEST_URI"]) ?
str_replace(RELATIVE_PATH_BASE, '',
$_SERVER["REQUEST_URI"]) : '_UNKNOWN_');
define("REQUEST_PATH_STRIP_QUERY",
REQUEST_QUERY ?
str_replace('?' . REQUEST_QUERY, '', REQUEST_PATH) : REQUEST_PATH);
// -----------------------------------------------------------------------
// DEFINE SITE PARAMETERS
// -----------------------------------------------------------------------
define("PRODUCTION", false);
define("PAGE_PATH_DEFAULT", US . 'index');
define("PAGE_PATH",
(REQUEST_PATH_STRIP_QUERY === US) ?
PAGE_PATH_DEFAULT : REQUEST_PATH_STRIP_QUERY);
array (
'LOCAL_PATH_BOOTSTRAP' => '/var/www/libraries/backend/Data/examples',
'URL_SEPARATOR' => '/',
'DS' => '/',
'PS' => ':',
'US' => '/',
'RELATIVE_PATH_ROOT' => '',
'LOCAL_PATH_ROOT' => '/var/www',
'HTTP_PATH_ROOT' => 'localhost:8888',
'RELATIVE_PATH_BASE' => '/libraries/backend/Data/examples',
'RELATIVE_PATH_APP' => '/libraries/backend/Data',
'RELATIVE_PATH_LIBRARY' => '/libraries/backend/Data/vendor',
'RELATIVE_PATH_HELPERS' => '/libraries/backend/Data/examples',
'RELATIVE_PATH_TEMPLATE' => '/libraries/backend/Data/examples/templates',
'RELATIVE_PATH_CONFIG' => '/libraries/backend/Data/examples/config',
'RELATIVE_PATH_PAGES' => '/libraries/backend/Data/examples/pages',
'RELATIVE_PATH_ASSET' => '/libraries/backend/Data/examples/assets',
'RELATIVE_PATH_ASSET_IMG' => '/libraries/backend/Data/examples/assets/img',
'RELATIVE_PATH_ASSET_CSS' => '/libraries/backend/Data/examples/assets/css',
'RELATIVE_PATH_ASSET_JS' => '/libraries/backend/Data/examples/assets/js',
'LOCAL_PATH_BASE' => '/var/www/libraries/backend/Data/examples',
'LOCAL_PATH_APP' => '/var/www/libraries/backend/Data',
'LOCAL_PATH_LIBRARY' => '/var/www/libraries/backend/Data/vendor',
'LOCAL_PATH_HELPERS' => '/var/www/libraries/backend/Data/examples',
'LOCAL_PATH_TEMPLATE' => '/var/www/libraries/backend/Data/examples/templates',
'LOCAL_PATH_CONFIG' => '/var/www/libraries/backend/Data/examples/config',
'LOCAL_PATH_PAGES' => '/var/www/libraries/backend/Data/examples/pages',
'LOCAL_PATH_ASSET' => '/var/www/libraries/backend/Data/examples/assets',
'LOCAL_PATH_ASSET_IMG' => '/var/www/libraries/backend/Data/examples/assets/img',
'LOCAL_PATH_ASSET_CSS' => '/var/www/libraries/backend/Data/examples/assets/css',
'LOCAL_PATH_ASSET_JS' => '/var/www/libraries/backend/Data/examples/assets/js',
'HTTP_PATH_BASE' => 'localhost:8888/libraries/backend/Data/examples',
'HTTP_PATH_APP' => 'localhost:8888/libraries/backend/Data',
'HTTP_PATH_LIBRARY' => false,
'HTTP_PATH_HELPERS' => false,
'HTTP_PATH_TEMPLATE' => false,
'HTTP_PATH_CONFIG' => false,
'HTTP_PATH_PAGES' => false,
'HTTP_PATH_ASSET' => 'localhost:8888/libraries/backend/Data/examples/assets',
'HTTP_PATH_ASSET_IMG' => 'localhost:8888/libraries/backend/Data/examples/assets/img',
'HTTP_PATH_ASSET_CSS' => 'localhost:8888/libraries/backend/Data/examples/assets/css',
'HTTP_PATH_ASSET_JS' => 'localhost:8888/libraries/backend/Data/examples/assets/js',
'REQUEST_QUERY' => false,
'REQUEST_METHOD' => 'GET',
'REQUEST_STATUS' => false,
'REQUEST_PROTOCOL' => 'http://',
'REQUEST_PATH' => '/',
'REQUEST_PATH_STRIP_QUERY' => '/',
'PRODUCTION' => false,
'PAGE_PATH_DEFAULT' => '/index',
'PAGE_PATH' => '/index',
)
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/subdir1/yourdocument.txt";
?>
<?php
define('SITE_ROOT', dirname(__FILE__));
$file_path = SITE_ROOT . '/Texts/MyInfo.txt';
?>
$root = dirname( __FILE__ );
$root = __DIR__;
$filePath = realpath(dirname(__FILE__));
$rootPath = realpath($_SERVER['DOCUMENT_ROOT']);
$htmlPath = str_replace($root, '', $filePath);
<?php
## DEFINE ROOTPATH
$check_data_exist = "";
$i_surf = 0;
// looking for mainpath.php at the aktiv folder or higher folder
while (!file_exists($check_data_exist."mainpath.php")) {
$check_data_exist .= "../";
$i_surf++;
// max 7 folder deep
if ($i_surf == 7) {
return false;
}
}
define("MAINPATH", ($check_data_exist ? $check_data_exist : ""));
?>
Finding the PHP Document Root
print getenv ("SCRIPT_NAME");
/product/description/index.php
print realpath(basename(getenv("SCRIPT_NAME")));
/usr/local/apache/share/htdocs/product/description/index.php
$localpath=getenv("SCRIPT_NAME");
$absolutepath=realpath($localPath);
// fix the Windows slashes
$absolutepath=str_replace("\\","/",$absolutepath);
$docroot=substr($absolutepath,0,strpos($absolutepath,
$localpath));
// an example of use
include($docroot."/includes/config.php");
PHP Include from Root
<img src="/images/logo.png" alt="logo" />
<?php include("header.php"); ?>
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/common/header.php";
include_once($path);
?>
<?php set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] ); ?>
ini_set('include_path', './' . PATH_SEPARATOR . "./common/". PATH_SEPARATOR . ini_get('include_path'));
set_include_path( implode( PATH_SEPARATOR, array(
$_SERVER['DOCUMENT_ROOT'],
get_include_path()
) ) );
include 'common/header.php';
function root_path() {
if(!preg_match("/^(http:\/\/)/", $_SERVER['HTTP_HOST'])) {
$server = "http://" . $_SERVER['HTTP_HOST'];
} else {
$server = $_SERVER['HTTP_HOST'];
}
if(!preg_match("/(\/)$/", $server)) $server = $server . '/';
$path = explode('/', dirname(htmlentities($_SERVER['PHP_SELF'])));
$path = $path[1];
if(!preg_match("/(\/)$/", $path)) $path = $path . '/';
return $server . $path;
}
php_include($_SERVER['DOCUMENT_ROOT'] . "/common/header.php");
Root path doesn’t work with php include
/home2/siteuserftp/public_html/test/
include($_SERVER['DOCUMENT_ROOT'].'/example/example.php')
include( "/example/example.php" );
<?php
$docroot = 'http://www.example.com/';
include ($docroot.'inc-header.php');
?>
127.0.0.1 www.example.com
allow_url_include = On
subst W: C:\Inetpub\wwwroot
include_path = ".;c:\php\active\includes;W:\"
doc_root = W:\
include '/common/common.inc'; // access to mapped W: root
include 'common/common.inc'; // access to W: within include_path
$r = trim(filter_input(INPUT_SERVER, 'DOCUMENT_ROOT', FILTER_SANITIZE_STRING));
if (substr($r, 0, 1) == '/')
{
define("PATCH_SEPARATOR", "/");
}
else
{
define("PATCH_SEPARATOR", "\\");
}
if (substr($r, -1) == PATCH_SEPARATOR)
{
include_once ($r . 'example/example.php');
}
else
{
include_once ($r . PATCH_SEPARATOR . 'example/example.php');
}
/var/www/namedir/ <= root
/var/www/namedir/example/example.php <= file to include
-- directory when i need the include --
/var/www/namedir/dir1/page.php
/var/www/namedir/dir1/dirA/page.php
/var/www/namedir/dir1/dirB/page.php
include (substr(dirname(__FILE__),0,strpos(dirname(__FILE__), '/dir1'))."/example/example.php");
/var/www/namesite/internalDirA/dirToInclude/example.php
/var/www/namesite/internalDirA/dir1/dirA/example.php
/var/www/namesite/internalDirA/dir1/dirB/example.php
/var/www/namesite/dirReserved/dirToInclude/example.php
/var/www/namesite/dirReserved/dir1/dirA/example.php
/var/www/namesite/dirReserved/dir1/dirB/example.php
include('../parent.php');
include('../../grand_parent.php');
What is Web Root
'/Users/user1/Documents/DEV/++htdocs/03_MySite/'
'/var/www/vhosts/MySite.com/httpdocs/');
'/Users/user1/Documents/DEV/++htdocs/03_MySite/'
'/var/www/vhosts/MySite.com/httpdocs/');
'http://local.dev3/'
'http://www.MySite.com/'
'http://local.dev3/'
'http://www.MySite.com/'
http://local.dev3/
function webRoot() {
return str_replace(
$_SERVER['PHP_SELF'],
'',
/* correct for windows slashes */
str_replace('\\\\','/',__FILE__)
);
}
echo '<pre>
PHP_SELF : ',$_SERVER['PHP_SELF'],'
__FILE__ : ',__FILE__,'
Web Root : ',webRoot(),'
</pre>';
PHP_SELF : /webRoot.php
__FILE__ : C:\\web\\webRoot.php
Web Root : C:/web
PHP_SELF : /webRoot.php
__FILE__ : /var/www/web3/web/webRoot.php
Web Root : /var/www/web3/web
PHP_SELF : /webRoot.php
__FILE__ : /home/cutcodedown/public_html/webRoot.php
Web Root : /home/cutcodedown/public_html
Keeping files above web root/directory
$root = dirname($_SERVER['DOCUMENT_ROOT']) . '/System/'; # Outside the public web folder.
require $root . 'foler/file.php';
$root = dirname($_SERVER['DOCUMENT_ROOT']) . '/System/'; # Outside the public web folder.
require $root . 'foler/file.php';
;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
include_path = "c:\\inetpub\\includes"
...
include("secrets.php");
- Author
- Recent Posts
I started writing code around 20 years ago, and throughout the years, I have gained a lot of expertise from hands-on experience as well as learning from others. This website has also grown with me and is now something that I am proud of.
The PHP root directory can be extracted through PHP built-in functions and constants. Moreover, the stated directory can be changed to your preferred path. So, our expertly written article will educate you about the various simple ways to access your root directory along with changing it.
Continue reading to get the PHP root path printed on your browser window in a few seconds.
JUMP TO TOPIC
- Get Root Directory: Use the Super Global Variable
- – Coding Example for Getting PHP Root Directory With $_SERVER
- Get Base Directory: Execute the Dirname() Function
- – Discussing the Levels Parameter in PHP Version 7 and Above
- – Coding Example for Getting PHP Root Directory by Using Dirname()
- PHP Root Path: Use Dirname() With __DIR__
- – Coding Example for Getting PHP Root Path By Using __DIR__
- How To Get To Root Directory in PHP: Use Chroot()
- – Coding Example for Using the Chroot() Function
- – Note:
- PHP Get Root Directory of Website: Going to the Top
- – Coding Example for Getting Root Directory of Website
- PHP Root Directory Path: Comparing the Magical Constants
- – Coding Example for Comparing the Magical Constants
- Winding Up
Get Root Directory: Use the Super Global Variable
You might find it hard to believe but the super global variable $_SERVER can help you in finding the PHP root directory path. Certainly, the PHP root path is stored on the “DOCUMENT_ROOT” element of the $_SERVER array. Therefore, accessing the given element will return the parent directory path accurately. Also, it would be best to note that the $DOCUMENT_ROOT element is defined in the server’s configuration file.
– Coding Example for Getting PHP Root Directory With $_SERVER
Suppose your current PHP script is created in the “main” directory, but now, you want to get the base directory. So, you’ll print $_SERVER[“DOCUMENT_ROOT”] to get your required results. What’s more, the output will contain the complete PHP root directory path. Also, you can easily identify the parent directory from the result returned by the $_SERVER[“DOCUMENT_ROOT”].
Please feel free to see how the $_SERVER array helps in your root directory search process:
<?php
// getting your current directory
echo getcwd();
// output: C:xampphtdocsmain
// printing the root directory path
echo $_SERVER[“DOCUMENT_ROOT”];
// output: C:xampphtdocs
?>
Get Base Directory: Execute the Dirname() Function
Certainly, you don’t need to worry if your currently installed version of PHP is below 5.3.0 because you can execute the dirname() function. The dirname() function will let you pass the required file or folder path and an optional number of levels. Next, the same function will return the PHP root directory path with maximum accuracy.
Furthermore, its syntax is right here: dirname(path, levels).
– Discussing the Levels Parameter in PHP Version 7 and Above
In PHP version 7 and above, the dirname() function allows you to specify the number of levels while acquiring the PHP root directory. You can pass an integer value that comes above one as the second argument to the dirname() function. For example, if you want to PHP get base directory that is one level above your current directory, then you’ll pass two and so on.
– Coding Example for Getting PHP Root Directory by Using Dirname()
Imagine having a script file saved in the “src” directory that exists in the “MyWebsite” directory with the path: “C:xampphtdocsMyWebsitesrc.” Now, let’s assume you also want to get the base directory that exists three levels above your script file. Here, the simplest way to pass the path of your current file to the dirname() function is by passing the __FILE__ constant to it. Next, you’ll pass three as the number of levels.
Please have a look at this code representation that depicts the stated example in the easiest possible manner so you can use it in your programming practice:
<?php
// printing your current directory
echo getcwd();
// output: C:xampphtdocsMyWebsitesrc
// printing the third level root directory path
echo dirname(__FILE__, 3);
// output: C:xampphtdocs
?>
PHP Root Path: Use Dirname() With __DIR__
Are you using a PHP version 5.3.0 and above, and looking for a solution to get the PHP root path? Then do nothing else except for passing the magical constant “__DIR__” to the dirname() function. The given constant will return the path of your current directory and the dirname() function will return the PHP root directory of the same.
– Coding Example for Getting PHP Root Path By Using __DIR__
For instance, let’s discuss a case in which the main directory of your PHP project is “MyProject” and it is saved in the “htdocs” folder located in the xampp folder in C drive. This hypothetical directory consists of two subfolders: “assets” and “images” and your current file “myFile.php” is located in the “assets” folder.
Now, you may want to PHP get base directory path of your current directory. Here, you’ll simply pass the magic constant __DIR__ to the dirname() function to acquire accurate results.
Please feel free to use the short code snippet we have provided for you below that implements the dirname() function with the __DIR__ constant:
<?php
// getting the root path of the assets directory
echo dirname(__DIR__);
// output: C:xampphtdocsMyProject
?>
How To Get To Root Directory in PHP: Use Chroot()
So, if you are a user of the BSD or GNU Operating System then here you’ll see how to get to root directory in PHP. You can set the current directory to “/” by implementing the chroot() function either in CGI, CLI, or Embed SAPI. Also, the same function changes the path of the PHP root directory. Hence, the incredible functionality of the chroot() function will amaze you to a great extent.
Undeniably, the given function accepts a directory that apparently changes the PHP root directory of the current process to the same, and makes “/” the current directory.
You will need to use this syntax in any relevant code you are planning to create: chroot(directory).
– Coding Example for Using the Chroot() Function
For example, let’s say you want to change the path of your root directory. Secondly, you also want to get to your root directory. In this case, you’ll use the chroot() function by following the syntax above. Consequently, you’ll have both of your requirements fulfilled.
Here is a code fragment to help you in switching to the root directory easily:
<?php
// echo your current directory
echo getcwd();
// output: C:xampphtdocsMyFolder
// using the chroot function
chroot(“/NewFolder/”);
// echo your current directory again
echo getcwd();
// output: /
?>
– Note:
The chroot() function doesn’t work on Windows Operating System while it requires root privileges on the systems stated above.
PHP Get Root Directory of Website: Going to the Top
Do you have a large website directory consisting of various directories, subdirectories, and files? Would you like to see the topmost level of your website directory without jumping through all the layers? Well, you can do this by applying a small trick with the combination of the explode() function and the $_SERVER variable. In the end, you’ll PHP get root directory of website without wasting your time in counting the levels backward.
– Coding Example for Getting Root Directory of Website
For instance, we are creating a hypothetical case in which your current file “newFile.php” has the path “C:xampphtdocswebsiteassetsmainpagesadmincontactnewFile.php.” But now, you want to access its topmost directory.
In the given scenario, you’ll use the explode function and convert the path returned by the $_SERVER[“DOCUMENT_ROOT”] into an array by using “/” as a separator. Next, you’ll access the first element of the resulting path array to get your PHP root directory.
Please go through the piece of code given below for more assistance:
<?php
// converting the root directory path string into an array
$path = explode(‘/’, $_SERVER[“DOCUMENT_ROOT”]);
// printing the first element of the root directory path array
echo $path[0]; // output: C:
?>
PHP Root Directory Path: Comparing the Magical Constants
Interestingly, the __DIR__ and __FILE__ constants provide almost similar results. The only exception between both of them is that the __DIR__ constant returns the path of your current directory. On the other hand, the __FILE__ constant gives back the path of your current file. Therefore, you will notice a difference of one level when you use them inside the dirname() function.
– Coding Example for Comparing the Magical Constants
Let’s assume that you are willing to find the results returned by the two magical constants and their effect with the dirname function
If you have found yourself in such a case, then you should follow these coding instructions to save your time:
<?php
echo __DIR__ . “<br>”;
// output: C:xampphtdocsMyFolder
echo dirname(__DIR__) . “<br>” ;
// output: C:xampphtdocs
echo __FILE__ . “<br>”;
// output: C:xampphtdocsMyFoldermyFile.php
echo dirname(__FILE__);
// output: C:xampphtdocsMyFolder
?>
Winding Up
Undoubtedly, being familiar with your PHP root directory path can be quite helpful while working on large projects. Having covered different ways to get the base directory path, here are some notable facts to help you ensure the correctness of your concepts:
- The $_SERVER[“DOCUMENT_ROOT”] returns the PHP root directory of your current file
- In PHP versions before 5.3, you can use the dirname() function with the __FILE__ constant and a level >= two to PHP get base directory of your current file
- In PHP version from 5.3 and over, you can use the dirname() function with the __DIR__ constant to PHP get base directory of your current directory
- You can get to the root directory by using the chroot() function in BSD and GNU Operating Systems
- The combo of the explode() function with $_SERVER[“DOCUMENT_ROOT”] serves to be an efficient way to get the root directory
The blocks of code given above will provide you with the results that’ll align with your current directory structure. You can also try placing your script in different folders to see how the returned paths change with every switch.
The PHP document root is the folder where a PHP script is running. When installing a script, web developers often need to know the document root. Although many pages scripted with PHP run on an Apache server, some run under Microsoft IIS on Windows. Apache includes an environment variable called DOCUMENT_ROOT, but IIS doesn’t. As a result, there are two methods for locating the PHP document root.
Finding the PHP Document Root Under Apache
Instead of emailing tech support for the document root and waiting for someone to respond, you can use a simple PHP script with getenv (), which provides a shortcut on Apache servers to the document root.
These few lines of code return the document root.
Finding the PHP Document Root Under IIS
Microsoft’s Internet Information Services was introduced with Windows NT 3.5.1 and has been included in most Windows releases since then—including Windows Server 2016 and Windows 10. It does not supply a shortcut to the document root.
To find the name of the currently executing script in IIS, begin with this code:
print getenv ("SCRIPT_NAME");
which returns a result similar to:
/product/description/index.php
which is the full path of the script. You don’t want the full path, just the name of the file for SCRIPT_NAME. To get it, use:
print realpath(basename(getenv("SCRIPT_NAME")));
which returns a result in this format:
/usr/local/apache/share/htdocs/product/description/index.php
To remove the code referring to the site-relative file and arrive at the document root, use the following code at the beginning of any script that needs to know the document root.
$localpath=getenv("SCRIPT_NAME");
$absolutepath=realpath($localPath);
// fix the Windows slashes
$absolutepath=str_replace("\\","/",$absolutepath);
$docroot=substr($absolutepath,0,strpos($absolutepath,
$localpath));
// an example of use
include($docroot."/includes/config.php");
This method, although more complex, runs on both IIS and Apache servers.