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.
- Get Root Directory: Use the Super Global Variable
- Get Base Directory: Execute the Dirname() Function
- PHP Root Path: Use Dirname() With __DIR__
- How To Get To Root Directory in PHP: Use Chroot()
- PHP Get Root Directory of Website: Going to the Top
- PHP Root Directory Path: Comparing the Magical Constants
- Winding Up
- Use the Super Global Variable
- – Coding Example for Getting PHP Root Directory With $_SERVER
- Execute the Dirname() Function
- – Discussing the Levels Parameter in PHP Version 7 and Above
- – Coding Example for Getting PHP Root Directory by Using Dirname()
- Use Dirname() With __DIR__
- – Coding Example for Getting PHP Root Path By Using __DIR__
- How To Get To Root Directory in PHP
- – Coding Example for Using the Chroot() Function
- PHP Get Root Directory of Website
- – Coding Example for Getting Root Directory of Website
- Comparing the Magical Constants
- – Coding Example for Comparing the Magical Constants
- Description
- Parameters
- Return Values
- Examples
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- Описание
- Индексы
- Примеры
- Примечания
- What is the document root in PHP?
- How do I know if my document is root?
- How do I change the root path in PHP?
- How do I find the root directory of a project?
- Where is my Public_html folder?
- Where is document root defined?
Use the Super Global Variable
You might find it hard to believe but the super global variable can help you in finding the PHP root directory path. Certainly, the PHP root path is stored on the 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
Please feel free to see how the $_SERVER array helps in your root directory search process:
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 . 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:
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 . 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:
How To Get To Root Directory in PHP
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
Here is a code fragment to help you in switching to the root directory easily:
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
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 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
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
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
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
(PHP 4, PHP 5, PHP 7, PHP 8)
— Gets the current working directory
Description
Parameters
This function has no parameters.
Return Values
Returns the current working directory on success, or false on
failure.
Examples
Example #1 example
The above example will output
something similar to:
/home/didou /home/didou/cvs
If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled,
the current working directory returned by
may be different from that returned by operating system interfaces.
External libraries (invoked through FFI)
which depend on the current working directory will be affected.
dave at corecomm dot us ¶
19 years ago
getcwd() returns the path of the "main" script referenced in the URL.
dirname(__FILE__) will return the path of the script currently executing.
I had written a script that required several class definition scripts from the same directory. It retrieved them based on filename matches and used getcwd to figure out where they were.
Didn't work so well when I needed to call that first script from a new file in a different directory.
1 year ago
given a link
/some/link->/some/location/path
with linux bash,
if within the linked drawer /some/link
cd .. goes upper link /some/
cd -P .. goes upper destination /some/location/
with php
fopen ("../file") goes upper destination /some/location/file
some others commented about ways obtaining the path below.
6 years ago
getcwd() appears to call the equivalent of PHP's realpath() on the path. It never returns symlinks, but always the actual directory names in the path to the current working directory.
15 years ago
hodgman at ali dot com dot au ¶
16 years ago
I use this code to replicate the pushd and popd DOS commands in PHP:
memandeemail at gmail dot com ¶
17 years ago
marcus at synchromedia dot co dot uk ¶
18 years ago
"On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does."
Just so you know, MacOS X is one of these variants (at least 10.4 is for me). You can make it work by applying 'chmod a+rx' to all folders from your site folder upwards.
leonbrussels at gmail dot com ¶
15 years ago
This is a function to convert a path which looks something like this:
To a proper directory path:
is really useful you want to compare two filepaths which are not necesarily in a It works in
bvidinli at gmail dot com ¶
14 years ago
if you link your php to /bin/linkedphp and your php is at for ex /home/actual.php
when you run linkedphp in somewhere in your filesystem,
getcwd returns /bin instead of working dir,
solution: use dirname(__FILENAME__) instead
ash at ashmckenzie dot org ¶
14 years ago
It appears there is a change in functionality in PHP5 from PHP4 when using the CLI tool. Here is the example: -
cat > foo.php << END
END
php -q /tmp/foo.php
PHP4 returns /tmp
PHP5 returns /
Something to be aware of.
troy dot cregger at gmail dot com ¶
16 years ago
Take care if you use getcwd() in file that you'll need to include (using include, require, or *_once) in a script located outside of the same directory tree.
7 years ago
Be aware when calling getcwd() in directories consisting of symlinks.
getcwd() is the equivalent of shell command "pwd -P" which resolves symlinks.
The shell command "pwd" is the equivalent of "pwd -L" which uses PWD from the environment without resolving symlinks. This is also the equivalent of calling getenv('PWD').
12 years ago
As you could read in
http://www.php.net/manual/en/features.commandline.differences.php
the CLI SAPI does - contrary to other SAPIs - NOT automatically change the current working directory to the one the started script resides in.
A very simple workaround to regain the behaviour you're used to from your "ordinary" webpage scripting is to include something like that at the beginning of your script:
// Note: all pathes stored in subsequent Variables end up with a DIRECTORY_SEPARATOR
// how to store the working directory "from where" the script was called:
() ) );// how to switch symlink-free to the folder the current file resides in:
) ) );// how to store the former folder in a variable:
// how to get a path one folder up if $my_folder ends with \class\ or /class/ :
// how to get a path one folder up in any case :
// how to make an array of OS-style-pathes from an array of unix-style-pathes
// (handy if you use config-files or so):
manux at manux dot org ¶
19 years ago
watch out:
working directory, and thus:
getcwd ()
is "/" while being into a register'ed shutdown function!!!
15 years ago
ab5602 at wayne dot edu ¶
15 years ago
If getcwd() returns nothing for you under Solaris with an NFS mounted subdirectory, you are running into an OS bug that is supposedly fixed in recent versions of Solaris 10. This same OS bug effects the include() and require() functions as well.
18 years ago
If your PHP cli binary is built as a cgi binary (check with php_sapi_name), the cwd functions differently than you might expect.
This can trip you up if you're writing command line scripts with php. You can override the CGI behavior by adding -C to the php call:
and then getcwd() behaves as it does in the CLI-compiled version.
Wolfgang M. Pauli ¶
15 years ago
If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link (similarly when parent etc. is symbolic link). There might be a better solution, but this worked for me (linux):
<? php
$cwd = exec('pwd');
?>
emailfire at gmail dot com ¶
17 years ago
(PHP 4, PHP 5, PHP 7, PHP 8)
— Получает имя текущего рабочего каталога
Описание
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает текущий рабочий каталог в случае успешного выполнения или false в
случае ошибки.
На некоторых вариантах Unix вернёт
false, если на каком-либо из родительских каталогов не
установлен режим чтения или поиска, даже если он установлен на
текущем каталоге. Больше информации о режимах доступа смотрите
в документации функции .
Примеры
Пример #1 Пример использования
Результатом выполнения данного примера
будет что-то подобное:
/home/didou /home/didou/cvs
Если PHP-интерпретатор собран с поддержкой ZTS (Zend Thread Safety), текущий рабочий каталог, возвращаемый , может отличаться от того, что возвращают интерфейсы операционной системы.
Буду задействованы внешние библиотеки (подключённые через FFI), использующие текущий рабочий каталог.
Смотрите также
dave at corecomm dot us ¶
19 years ago
getcwd() returns the path of the "main" script referenced in the URL.
dirname(__FILE__) will return the path of the script currently executing.
I had written a script that required several class definition scripts from the same directory. It retrieved them based on filename matches and used getcwd to figure out where they were.
Didn't work so well when I needed to call that first script from a new file in a different directory.
1 year ago
given a link
/some/link->/some/location/path
with linux bash,
if within the linked drawer /some/link
cd .. goes upper link /some/
cd -P .. goes upper destination /some/location/
with php
fopen ("../file") goes upper destination /some/location/file
some others commented about ways obtaining the path below.
6 years ago
getcwd() appears to call the equivalent of PHP's realpath() on the path. It never returns symlinks, but always the actual directory names in the path to the current working directory.
15 years ago
hodgman at ali dot com dot au ¶
16 years ago
I use this code to replicate the pushd and popd DOS commands in PHP:
memandeemail at gmail dot com ¶
17 years ago
marcus at synchromedia dot co dot uk ¶
18 years ago
"On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does."
Just so you know, MacOS X is one of these variants (at least 10.4 is for me). You can make it work by applying 'chmod a+rx' to all folders from your site folder upwards.
leonbrussels at gmail dot com ¶
15 years ago
This is a function to convert a path which looks something like this:
To a proper directory path:
is really useful you want to compare two filepaths which are not necesarily in a It works in
bvidinli at gmail dot com ¶
14 years ago
if you link your php to /bin/linkedphp and your php is at for ex /home/actual.php
when you run linkedphp in somewhere in your filesystem,
getcwd returns /bin instead of working dir,
solution: use dirname(__FILENAME__) instead
ash at ashmckenzie dot org ¶
14 years ago
It appears there is a change in functionality in PHP5 from PHP4 when using the CLI tool. Here is the example: -
cat > foo.php << END
END
php -q /tmp/foo.php
PHP4 returns /tmp
PHP5 returns /
Something to be aware of.
troy dot cregger at gmail dot com ¶
16 years ago
Take care if you use getcwd() in file that you'll need to include (using include, require, or *_once) in a script located outside of the same directory tree.
7 years ago
Be aware when calling getcwd() in directories consisting of symlinks.
getcwd() is the equivalent of shell command "pwd -P" which resolves symlinks.
The shell command "pwd" is the equivalent of "pwd -L" which uses PWD from the environment without resolving symlinks. This is also the equivalent of calling getenv('PWD').
12 years ago
As you could read in
http://www.php.net/manual/en/features.commandline.differences.php
the CLI SAPI does - contrary to other SAPIs - NOT automatically change the current working directory to the one the started script resides in.
A very simple workaround to regain the behaviour you're used to from your "ordinary" webpage scripting is to include something like that at the beginning of your script:
// Note: all pathes stored in subsequent Variables end up with a DIRECTORY_SEPARATOR
// how to store the working directory "from where" the script was called:
() ) );// how to switch symlink-free to the folder the current file resides in:
) ) );// how to store the former folder in a variable:
// how to get a path one folder up if $my_folder ends with \class\ or /class/ :
// how to get a path one folder up in any case :
// how to make an array of OS-style-pathes from an array of unix-style-pathes
// (handy if you use config-files or so):
manux at manux dot org ¶
19 years ago
watch out:
working directory, and thus:
getcwd ()
is "/" while being into a register'ed shutdown function!!!
15 years ago
ab5602 at wayne dot edu ¶
15 years ago
If getcwd() returns nothing for you under Solaris with an NFS mounted subdirectory, you are running into an OS bug that is supposedly fixed in recent versions of Solaris 10. This same OS bug effects the include() and require() functions as well.
18 years ago
If your PHP cli binary is built as a cgi binary (check with php_sapi_name), the cwd functions differently than you might expect.
This can trip you up if you're writing command line scripts with php. You can override the CGI behavior by adding -C to the php call:
and then getcwd() behaves as it does in the CLI-compiled version.
Wolfgang M. Pauli ¶
15 years ago
If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link (similarly when parent etc. is symbolic link). There might be a better solution, but this worked for me (linux):
<? php
$cwd = exec('pwd');
?>
emailfire at gmail dot com ¶
17 years ago
(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 the document root in PHP?
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.
How do I know if my document is root?
The DocumentRoot is the top-level directory in the document tree visible from the web and this directive sets the directory in the configuration from which Apache2 or HTTPD looks for and serves web files from the requested URL to the document root.
How do I change the root path in PHP?
You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT .
How do I find the root directory of a project?
So here’s what I figured out.
- create a blank python file in the root dir -> I call this beacon.py. (assuming that the project root is in the PYTHONPATH so it can be imported)
- add a few lines to my module/class which I call here not_in_root.py . This will import the beacon.py module and get the path to that module.
Where is my Public_html folder?
public_html folder is located inside your File Manager in your cPanel.
Where is document root defined?
The document root is a directory (a folder) that is stored on your host’s servers and that is designated for holding web pages. When someone else looks at your web site, this is the location they will be accessing.
You might know the DOCUMENT_ROOT value of the $_SERVER array. This value indicates the absolute location of the site directory where pages are served. In short, it’s the public folder of site as defined in the server’s configuration. Here’s a quick example :
If any page in the server, even if it is in many sub folders, the DOCUMENT_ROOT value will be the same.
This is totally depended on the site’s configuration. This value won’t be the same in your localhost server and on the server in the web.
Any library will have a file that’s loaded first. As an example, we assume it as «load.php» in the «library» directory and this is the file which includes it :
<?php
include "library/load.php";
?><?php
include $_SERVER["DOCUMENT_ROOT"] . "/library/file2.php";
?>But, we cannot be sure that the directory containing the library is named «library». So, we should calculate it in the correct way :
<?php
include realpath( dirname(__FILE__) ) . "/file2.php";
?>The above will work in all server environments which run PHP 5. The above code can be shortened in another way :
<?php
include realpath(__DIR__) . "/file2.php";
?>Both the ways is the same. Note that we are obtaining the absolute path of the «library» directory from the «load.php» file. So, we don’t need to add «library» before «/file2.php».






