PHPのお勉強!

PHP TOP

$_SERVER

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_SERVERサーバー情報および実行時の環境情報

説明

$_SERVER は、ヘッダ、パス、スクリプトの位置のような 情報を有する配列です。この配列のエントリは、Web サーバーにより 生成されます。全ての Web サーバーがこれら全てを提供する保証はありません。 サーバーは、これらのいくつかを省略したり、この一覧にない他のものを 定義する可能性があります。しかし、これらの変数のほとんどは、 » CGI/1.1 specification で定義されています。したがって、これらのほとんどは定義されていることを 期待することができます。

注意: PHP を コマンドライン から実行している場合、 これらの変数のほとんどは利用できないか、 なんの意味も持ちません。

以下に示された要素に加え、 PHP はリクエストヘッダから追加の要素を生成します。 それらの要素は HTTP_ で始まり、 その後にヘッダの名前が続き、 かつ大文字に変換され、ハイフンがアンダースコアになります。 たとえば、 Accept-Language ヘッダは $_SERVER['HTTP_ACCEPT_LANGUAGE'] として利用可能です。

インデックス

'PHP_SELF'
現在実行しているスクリプトのファイル名です。 ドキュメントルートから取得されます。 例えば、http://example.com/foo/bar.php というアドレス上にあるスクリプトでは $_SERVER['PHP_SELF']/foo/bar.php となります。 __FILE__ 定数 には、カレント(すなわち読み込まれた)ファイルのパスとファイル名が含まれます。 PHP がコマンドラインから実行される場合、 この変数にはスクリプト名が含まれます。
'argv'
スクリプトに渡された引数の配列です。スクリプトがコマンドラインから 実行された場合、C 言語スタイルでコマンドライン引数に アクセスすることができます。GET メソッドを通してコールされた場合には 検索引数が格納されます。
'argc'
スクリプトに渡されたコマンドライン引数の数 (コマンドラインから実行した場合) です。
'GATEWAY_INTERFACE'
サーバーが使用している CGI のバージョンです。 例 'CGI/1.1'
'SERVER_ADDR'
現在のスクリプトが実行されているサーバーの IP アドレスです。
'SERVER_NAME'
現在のスクリプトが実行されているサーバーのホスト名です。 スクリプトがバーチャルホスト上で実行されている場合は そのバーチャルホスト名となります。

注意: Apache 2 では、UseCanonicalName = OnServerName を設定する必要があります。 そうしなければ、この値はクライアントが提供するホスト名を指すようになってしまい、無意味です。 また、セキュリティ的な意味合いでこの値に頼ってはいけません。

'SERVER_SOFTWARE'
レスポンスヘッダ上に書かれている、 サーバーの認識文字列です。
'SERVER_PROTOCOL'
ページがリクエストされた際のプロトコル名とバージョンです。 例. 'HTTP/1.0'
'REQUEST_METHOD'
ページにアクセスする際に使用されたリクエストのメソッド名です。 'GET', 'HEAD', 'POST', 'PUT' など。

注意:

リクエストのメソッドが HEAD だった場合、 PHP スクリプトはヘッダを送信した後(言い換えれば、 出力バッファリングを行わずに全出力を処理した後)に終了します。

'REQUEST_TIME'
リクエストの開始時のタイムスタンプ。
'REQUEST_TIME_FLOAT'
リクエストの開始時のタイムスタンプ (マイクロ秒までの精度)。
'QUERY_STRING'
ページがアクセスされた際にもし検索引数があればそれが格納されます。
'DOCUMENT_ROOT'
現在実行されているスクリプトが存在するドキュメントルート ディレクトリです。サーバーのコンフィグレーションファイルで 定義されています。
'HTTPS'
スクリプトが HTTPS プロトコルを通じて実行されている場合に 空でない値が設定されます。
'REMOTE_ADDR'
現在ページをみているユーザーの IP アドレス。
'REMOTE_HOST'
現在のページにアクセスしているホスト名。DNS の逆引き検索は ユーザーの REMOTE_ADDR に基づいています。

注意: Web サーバーがこの値を生成できるように設定されている必要があります。 例えば Apache の場合 HostnameLookups Onhttpd.conf に設定されていなければこの値は生成されません。 gethostbyaddr() もご覧ください。

'REMOTE_PORT'
ユーザーのマシンから Web サーバーへの通信に使用されているポート番号
'REMOTE_USER'
認証されたユーザー。
'REDIRECT_REMOTE_USER'
リクエストが内部でリダイレクトされた場合の認証されたユーザー。
'SCRIPT_FILENAME'

現在実行されているスクリプトの絶対パス

注意:

file.php あるいは ../file.php のような相対パスを指定して CLI でスクリプトが実行されている場合、 $_SERVER['SCRIPT_FILENAME'] には ユーザーが指定した相対パスが含まれます。

'SERVER_ADMIN'
Web サーバーの設定ファイルの SERVER_ADMIN (Apache の場合)ディレクティブ にセットされている値。スクリプトがバーチャルホスト上で 実行されている場合、バーチャルホストに対して値が定義されます。
'SERVER_PORT'
Web サーバーの通信ポートとして使用されているポート番号。デフォルトでは '80' ですが、例えば SSL を使用している場合は セキュア HTTP ポートとして設定されている値に変わります。

注意: Apache 2 では、UseCanonicalName = On だけでなく UseCanonicalPhysicalPort = On も設定しないと物理ポート (実際のポート) を取得できません。設定しなければ、 この値は詐称できる状態になり、 物理ポートを返さなくなるかもしれません。 セキュリティに依存するコンテキストで、この値に頼るのは安全ではありません。

'SERVER_SIGNATURE'
サーバー上で生成されたページに追加される、 サーバーのバージョン名とバーチャルホスト名の文字列。 Web サーバーの設定で有効になっていることが必要です。
'PATH_TRANSLATED'
バーチャルからリアルへのマッピングがなされた後の、 現在のスクリプトのファイルシステム上(ドキュメントルートではなく) でのパス。

注意: Apache 2 ユーザーは、PATH_INFO を定義するために httpd.conf の中で AcceptPathInfo = On を使用することが可能です。

'SCRIPT_NAME'
現在のスクリプトのパス。 スクリプト自身のページを指定するのに有用です。 __FILE__ 定数には、カレント(すなわち読み込まれた)ファイルのパスとファイル名が 含まれます。
'REQUEST_URI'
ページにアクセスするために指定された URI。例えば、 '/index.html'
'PHP_AUTH_DIGEST'
HTTP ダイジェスト認証を 行っている場合、クライアントから送られた 'Authorization' ヘッダの 内容が設定されます(適切な認証処理を行うために利用します)。
'PHP_AUTH_USER'
HTTP 認証しているときにそのユーザー名がセットされます。
'PHP_AUTH_PW'
HTTP 認証しているときにそのユーザーの パスワードがセットされます。
'AUTH_TYPE'
HTTP 認証しているときにその認証形式がセットされます。
'PATH_INFO'
実際のスクリプトファイル名とクエリ文字列の間にある、クライアントが提供するパス名情報。 たとえば、現在のスクリプトに http://www.example.com/php/path_info.php/some/stuff?foo=bar という URI でアクセスしていた場合の $_SERVER['PATH_INFO']/some/stuff となります。
'ORIG_PATH_INFO'
PHP で処理される前の 'PATH_INFO' の原本。

例1 $_SERVER の例

<?php
echo $_SERVER['SERVER_NAME'];
?>

上の例の出力は、 たとえば以下のようになります。

www.example.com

注意

注意:

これは 'スーパーグローバル' あるいは自動グローバル変数と呼ばれるものです。 スクリプト全体を通してすべてのスコープで使用することができます。 関数やメソッドの内部で使用する場合にも global $variable; とする必要はありません。

add a note

User Contributed Notes 40 notes

up
157
Vladimir Kornea
15 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.
up
56
vcoletti at tiscali dot it
4 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.
up
38
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";}

?>
up
26
jonbarnett at gmail dot com
15 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.
up
37
Lord Mac
14 years ago
An even *more* improved version...

<?php
phpinfo
(32);
?>
up
24
pierstoval at example dot com
7 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...)
up
13
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
}
up
13
chris at ocproducts dot com
7 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.
up