$_SERVER

$HTTP_SERVER_VARS [نامطلوب]

$_SERVER -- $HTTP_SERVER_VARS [نامطلوب]اطلاعات محیط اجرا و سرور

Description

$_SERVER یک آرایه شامل اطلاعات مانند سرآیند مسیرها و محل اسکریپت است. ورودی این آرایه در وب‌سرور ساخته می‌شود. تضمینی برای ساخته شدن این آرایه در هر وب‌سرور وجود ندارد . سرورها ممکن است بعضی از آنها را حذف نمایند یا چیزهای دیگری فراهم نمایند. بیشتر این متغیرهای در » ویژگی‌هایCGI 1.1 فهرست شده‌اند پس می‌توانید آنها را بیابید.

$HTTP_SERVER_VARS همان اطلاعات را داشته اما یک superglobal نیست. (توجه کنید که $HTTP_SERVER_VARS و $_SERVER متغیرهای متفاوتی هستند و PHP با آنها بصور متفاوت رفتار می‌کند)

Indices

شما ممکن است اجزای زیر را در $_SERVER بیابید یا نه. توجه کنید اجزای کمی یا حداقل تعدادی از آنها مو جود خواهند بود (یا معنی خواهند داشت) اگر PHP را از طریق خط فرمان اجرا می‌نمایید.

'PHP_SELF'
نام فایل فعلی در حال اجرا در اسکریپت نسبت به مکان نسبی ریشه. برای نمونه $_SERVER['PHP_SELF'] در یک اسکریپت آدرس http://example.com/test.php/foo.bar ٬ /test.php/foo.bar خواهد بود. ثابت __FILE__ مسیر کامل و نام فایل فعلی را خواهد داشت (به عنوان نمونه اضافه شده). اگر PHP به عنوان پردازنده خط فرمان مورد استفاده قرار گیرد این متغیر نام اسکریپت را از زمان PHP 4.3.0 خواهد داشت. پیش از آن در دسترس نبوده است.
'$argv'
آرایه آرگومان‌ٰهای داده شده به این اسکریپت. وقتی اسکریپت از خط فرمان اجرا شود دسترسی همانند C به پارامترهای خط فرمان خواهد داد. وقتی از طریق متد GET فراخوانی شود این متغیر رشته درخواست را خواهد داشت.
'$argc'
تعداد پارامترهای ارسالی به اسکریپت را دارد (اگر در خط فرمان اجرا شود).
'GATEWAY_INTERFACE'
چه نسخه‌ای از ویژگی‌های CGIدر سرور مورد استفاده است; برای نمونه 'CGI/1.1'.
'SERVER_ADDR'
آدرس IP اجرا کننده اسکریپت فعلی.
'SERVER_NAME'
نام میزبان سرور در اسکریپت فعلی. اگر اسکریپت در یک میزبان مجازی اجرا می‌شود مقدار مشخص شده توسط این میزبان در آن خواهد بود.
'SERVER_SOFTWARE'
رشته تشخیص سرور داده شده در سرآیند درخواست‌ها.
'SERVER_PROTOCOL'
نام و نسخه پروتکل از طریق درخواست صفحه.برای نمونه 'HTTP/1.0';
'REQUEST_METHOD'
کدام شیوه درخواست برای دسترسی به صفحه مورد استفاده قرار گرفته سات. برای نمونه 'GET'٬ 'HEAD'٬ 'POST'٬ 'PUT'.

Note:

اسکریپت PHP پس از فرستادن سرآیندها پایان خواهد یافت (به معنای تولید خروجی بدون قرار دادن آن در بافر) اگر شیوه درخواست HEAD باشد.

'REQUEST_TIME'
برچسب زمانی شروع درخواست. موجود از زمان PHP 5.1.0.
'QUERY_STRING'
رشته پرس و جو اگر از طریق صفحه به آنها دسترسی درخواست شده باشد.
'DOCUMENT_ROOT'
ریشه سند در اسکریپت فعلی در حال اجرا که در فایل تنظیمات سرور تنظیم شده باشد.
'HTTP_ACCEPT'
محتویات سرآیندAccept: از درخواست فعلی اگر وجود داشته باشد.
'HTTP_ACCEPT_CHARSET'
محتویات سرآیند Accept-Charset: از درخواست فعلی اگر وجود داشته باشد. نمونه: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
محتویات سرآیند Accept-Encoding: از درخواست فعلی اگر وجود داشته باشد. نمونه: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
محتویات سرآیند Accept-Language: از درخواست فعلی اگر وجود داشته باشد. نمونه: 'en'.
'HTTP_CONNECTION'
محتویات سرآیند Connection: از درخواست فعلی اگر وجود داشته باشد. نمونه: 'Keep-Alive'.
'HTTP_HOST'
محتویات سرآیند Host: از درخواست فعلی اگر وجود داشته باشد.
'HTTP_REFERER'
آدرس صفحه (اگر باشد) که توسط عامل کاربر در صفحه فعلی به آن اشاره می‌شود. تمام عوامل کاربر نمی‌توانند این مقدار را تنظیم نمایند و بعضی از آنها توانایی تغییر HTTP_REFERER را به عنوان یک ویژگی دارا هستند. واقعا نمی‌توان به آن اعتماد کرد.
'HTTP_USER_AGENT'
محتویات سرآیند User-Agent: از درخواست فعلی اگر وجود داشته باشد. این رشته نمایش‌دهنده عامل کاربر در حال دسترسی به صفحه فعلی است. یک نمونه معمول: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). در میان باقی چیزها شما می‌توانید از این مقدار به همراه get_browser() برای چسباندن خروجی صفحه خود به توانایی عامل کاربر است. agent.
'HTTPS'
اگر صفحه از طریق HTTP مورد دسترسی واقع شده باشد این مقدار غیر خالی خواهد بود.

Note: توجه کنید هنگام استفاده از ISAPI به همراه IIS مقدار برابر با off خواهد بود اگر درخواست از طریق پروتکل HTTPS نباشد.

'REMOTE_ADDR'
آدرس IP که کاربر صفحه را با آن می‌بیند.
'REMOTE_HOST'
نام میزبان کاربر که از آن صفحه را می‌بیند. جستجوی بازگشتی dns براساس REMOTE_ADDR کاربر است.

Note: وب سرور شما باید بگونه‌ای تنظیم شده باشد که این متغیر را بسازد. برای نمونه در آپاچی شما نیاز به HostnameLookups On در httpd.conf دارید تا وجود داشته باشد. همچنین gethostbyaddr() را ببینید.

'REMOTE_PORT'
پورت مورد استفاده در ماشین کاربر برای ارتباط با وب سرور.
'SCRIPT_FILENAME'

مسیر مطلق اسکریپت فعلی در حال اجرا.

Note:

اگر اسکریپت با استفاده از CLI دیده می‌شود مسیر نسبی مانند file.php یا ../file.php٬ $_SERVER['SCRIPT_FILENAME'] مسیر نسبی تعیین شده توسط کاربر را نشان خواهد داد.

'SERVER_ADMIN'
مقدار داده شده به شبه جملهSERVER_ADMIN (برای Apache) در فایل تنظیمات وب سرور. اگر اسکریپت بر میزبان مجازی عمل نماید این مقدار توسط میزبان مجازی تعریف خواهد شد.
'SERVER_PORT'
پورت استفاده شده در ماشین سرور توسط وب سرور برای ارتباطات. تنظیم پیش‌فرض '80' خواهد بود; استفاده از SSL برای نمونه این مقدار را به هر پورت امن HTTP تغییر می‌دهد.
'SERVER_SIGNATURE'
رشته دارای نسخه سرور و نام میزبان مجازی که در صفحات ساخته شده توسط سرور در صورت فعال بودن اضافه می‌گردد.
'PATH_TRANSLATED'
سیستم فایل- (نه ریشه سند) براساس مسیر اسکریپت فعلی پس از انجام هر گونه تطبیق مجازی به حقیقی توسط سرور.

Note: از زمان PHP 4.3.2 PATH_TRANSLATED دیگر در آپاچی ۲ SAPI برخلاف موقعیت آپاچی ۱ روشن نیست. در آپاچی ۱ همان مقدار متغیر سرور SCRIPT_FILENAME علارغم محبوب نبودن در آپاچی است. این تغییر برای پیروی از CGI است PATH_TRANSLATED تنها باید در صورتی موجود باشد که PATH_INFO تعریف شده باشد. کاربران Apache 2 از AcceptPathInfo = On در httpd.conf برای تعریف PATH_INFO استفاده نمی‌کند.

'SCRIPT_NAME'
محتوی مسیر اسکریپت فعلی است. این برای ضفحاتی سودمند است که باید بر خود اشاره نمایند. ثابت __FILE__ مسیر کامل و نام فایل فعلی را دارد (به عنوان نمونه اضافه شده).
'REQUEST_URI'
URI برای دسترسی به این صفحه; برای نمونه '/index.html'.
'PHP_AUTH_DIGEST'
هنگام اجرا تحت آپاچی به عنوان ماجول تجزیه داده‌های تایید هویت HTTP این متغیر برابر با سرآیند 'Authorization' فرستاده شده توسط مشتری است (که شما باید سپس از آن استفاده نمایید تا تایید صحت آن را انجام دهید).
'PHP_AUTH_USER'
هنگام اجرا تحت Apache یا IIS (ISAPI بر PHP 5) به عنوان ماجول تایید هویت HTTP این متغیر نشان‌دهنده کلمه کاربری فراهم شده است.
'PHP_AUTH_PW'
هنگام اجرا تحت Apache یا IIS (ISAPI بر PHP 5) به عنوان ماجول تایید هویتas module doing 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.

Changelog

Version Description
4.1.0 معرفی $_SERVER موجب نامطلوب شدن $HTTP_SERVER_VARS شد.

Examples

Example #1 نمونه $_SERVER

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

The above example will output something similar to:

www.example.com

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

add a note add a note

User Contributed Notes 50 notes

up
53
zeufonlinux at gmail dot com
1 year ago
Just a PHP file to put on your local server (as I don't have enough memory)

<?php
$indicesServer
= array('PHP_SELF',
'argv',
'argc',
'GATEWAY_INTERFACE',
'SERVER_ADDR',
'SERVER_NAME',
'SERVER_SOFTWARE',
'SERVER_PROTOCOL',
'REQUEST_METHOD',
'REQUEST_TIME',
'REQUEST_TIME_FLOAT',
'QUERY_STRING',
'DOCUMENT_ROOT',
'HTTP_ACCEPT',
'HTTP_ACCEPT_CHARSET',
'HTTP_ACCEPT_ENCODING',
'HTTP_ACCEPT_LANGUAGE',
'HTTP_CONNECTION',
'HTTP_HOST',
'HTTP_REFERER',
'HTTP_USER_AGENT',
'HTTPS',
'REMOTE_ADDR',
'REMOTE_HOST',
'REMOTE_PORT',
'REMOTE_USER',
'REDIRECT_REMOTE_USER',
'SCRIPT_FILENAME',
'SERVER_ADMIN',
'SERVER_PORT',
'SERVER_SIGNATURE',
'PATH_TRANSLATED',
'SCRIPT_NAME',
'REQUEST_URI',
'PHP_AUTH_DIGEST',
'PHP_AUTH_USER',
'PHP_AUTH_PW',
'AUTH_TYPE',
'PATH_INFO',
'ORIG_PATH_INFO') ;

echo
'<table cellpadding="10">' ;
foreach (
$indicesServer as $arg) {
    if (isset(
$_SERVER[$arg])) {
        echo
'<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ;
    }
    else {
        echo
'<tr><td>'.$arg.'</td><td>-</td></tr>' ;
    }
}
echo
'</table>' ;

/*

That will give you the result of each variable like (if the file is server_indices.php at the root and Apache Web directory is in E:\web) :

PHP_SELF    /server_indices.php
argv    -
argc    -
GATEWAY_INTERFACE    CGI/1.1
SERVER_ADDR    127.0.0.1
SERVER_NAME    localhost
SERVER_SOFTWARE    Apache/2.2.22 (Win64) PHP/5.3.13
SERVER_PROTOCOL    HTTP/1.1
REQUEST_METHOD    GET
REQUEST_TIME    1361542579
REQUEST_TIME_FLOAT    -
QUERY_STRING   
DOCUMENT_ROOT    E:/web/
HTTP_ACCEPT    text/html,application/xhtml+xml,application/xml;q=0.9,*/
*;q=0.8
HTTP_ACCEPT_CHARSET    ISO
-8859-1,utf-8;q=0.7,*;q=0.3
HTTP_ACCEPT_ENCODING    gzip
,deflate,sdch
HTTP_ACCEPT_LANGUAGE    fr
-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
HTTP_CONNECTION    keep
-alive
HTTP_HOST    localhost
HTTP_REFERER    http
://localhost/
HTTP_USER_AGENT    Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17
HTTPS   
-
REMOTE_ADDR    127.0.0.1
REMOTE_HOST   
-
REMOTE_PORT    65037
REMOTE_USER   
-
REDIRECT_REMOTE_USER    -
SCRIPT_FILENAME    E:/web/server_indices.php
SERVER_ADMIN    myemail
@personal.us
SERVER_PORT    80
SERVER_SIGNATURE   
PATH_TRANSLATED   
-
SCRIPT_NAME    /server_indices.php
REQUEST_URI   
/server_indices.php
PHP_AUTH_DIGEST   
-
PHP_AUTH_USER    -
PHP_AUTH_PW    -
AUTH_TYPE    -
PATH_INFO    -
ORIG_PATH_INFO    -

*/
?>
up
16
Lord Mac
5 years ago
An even *more* improved version...

<?php
phpinfo
(32);
?>
up
17
Vladimir Kornea
5 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
7
cupy at email dot cz
5 years ago
Tech note:
$_SERVER['argc'] and $_SERVER['argv'][] has some funny behaviour,
used from linux (bash) commandline, when called like
"php ./script_name.php 0x020B"
there is everything correct, but
"./script_name.php 0x020B"
is not correct - "0" is passed instead of "0x020B" as $_SERVER['argv'][1] - see the script below.
Looks like the parameter is not passed well from bash to PHP.
(but, inspected on the level of bash, 0x020B is understood well as $1)

try this example:

------------->8------------------
cat ./script_name.php
#! /usr/bin/php

if( $_SERVER['argc'] == 2)
  {
    // funny... we have to do this trick to pass e.g. 0x020B from parameters
    // ignore this: "PHP Notice:  Undefined offset:  2 in ..."
    $EID = $_SERVER['argv'][1] + $_SERVER['argv'][2] + $_SERVER['argv'][3];
  }
else
   {        // default
     $EID = 0x0210; // PPS failure
   }
up
14
MarkAgius at markagius dot co dot uk
3 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
11
Richard York
5 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)
  }
up
6
rulerof at gmail dot com
4 years ago
I needed to get the full base directory of my script local to my webserver, IIS 7 on Windows 2008.

I ended up using this:

<?php
function GetBasePath() {
    return
substr($_SERVER['SCRIPT_FILENAME'], 0, strlen($_SERVER['SCRIPT_FILENAME']) - strlen(strrchr($_SERVER['SCRIPT_FILENAME'], "\\")));
}
?>

And it returned C:\inetpub\wwwroot\<applicationfolder> as I had hoped.
up
6
silverquick at gmail dot com
6 years ago
I think the HTTPS element will only be present under Apache 2.x. It's not in the list of "special" variables here:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond
But it is here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond
up
12
chris
5 years ago
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
up
5
jonbarnett at gmail dot com
5 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
6
krinklemail at gmail dot com
1 year 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
up
3
wyattstorch42 at outlook dot com
1 year ago
<?php
/*
* I wrote this because I was including a file with classes in it. Let's say that
* I have a contact page at mysite.com/contact/index.php and a Form class at
* mysite.com/classes/Form.php. So in index.php, I have this statement:
* require '../classes/Form.php';
* The Form class includes a method to generate the HTML markup for a number of
* form elements, including a CAPTCHA image and associated text field. To do so,
* it must generate an <img /> element and give it a src of Form.php?captcha.
* But I wanted it to automatically generate a src attribute without index.php
* giving it a relative path. This script comes in handy by automatically
* locating the directory that contains the included file (Form.php) and converting
* it from an absolute path to a relative path that could be used for an img src,
* an a href, a link href, etc.
*/
function relativeURL () {
   
$dir = str_replace('\\', '/', __DIR__);
       
// Resolves inconsistency with PATH_SEPARATOR on Windows vs. Linux
        // Use dirname(__FILE__) in place of __DIR__ for older PHP versions
   
return substr($dir, strlen($_SERVER['DOCUMENT_ROOT']));
       
// Clip off the part of the path outside of the document root
}

/*
*contact/index.php
*/
require '../classes/Form.php';
new
Form()->drawCaptchaField();
   
// Writes: <img src="/classes/Form.php?captcha" />

   
/*
* classes/Form.php
*/
if (isset($_GET['captcha'])) {
   
// generate/return CAPTCHA image
}

class
Form {
   
// ...
   
public function drawCaptchaField () {
        echo
'<img src="'.relativeURL().'?captcha" />';
    }
}
?>
up
10
mirko dot steiner at slashdevslashnull dot de
5 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.1

foreach (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
)
up
8
@44it
1 year ago
All the $_SERVER[''] In php :

<?php

echo "PHP_SELF : " . $_SERVER['PHP_SELF'] . "<br />";
echo
"GATEWAY_INTERFACE : " . $_SERVER['GATEWAY_INTERFACE'] . "<br />";
echo
"SERVER_ADDR : " . $_SERVER['SERVER_ADDR'] . "<br />";
echo
"SERVER_NAME : " . $_SERVER['SERVER_NAME'] . "<br />";
echo
"SERVER_SOFTWARE : " . $_SERVER['SERVER_SOFTWARE'] . "<br />";
echo
"SERVER_PROTOCOL : " . $_SERVER['SERVER_PROTOCOL'] . "<br />";
echo
"REQUEST_METHOD : " . $_SERVER['REQUEST_METHOD'] . "<br />";
echo
"REQUEST_TIME : " . $_SERVER['REQUEST_TIME'] . "<br />";
echo
"REQUEST_TIME_FLOAT : " . $_SERVER['REQUEST_TIME_FLOAT'] . "<br />";
echo
"QUERY_STRING : " . $_SERVER['QUERY_STRING'] . "<br />";
echo
"DOCUMENT_ROOT : " . $_SERVER['DOCUMENT_ROOT'] . "<br />";
echo
"HTTP_ACCEPT : " . $_SERVER['HTTP_ACCEPT'] . "<br />";
echo
"HTTP_ACCEPT_CHARSET : " . $_SERVER['HTTP_ACCEPT_CHARSET'] . "<br />";
echo
"HTTP_ACCEPT_ENCODING : " . $_SERVER['HTTP_ACCEPT_ENCODING'] . "<br />";
echo
"HTTP_ACCEPT_LANGUAGE : " . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . "<br />";
echo
"HTTP_CONNECTION : " . $_SERVER['HTTP_CONNECTION'] . "<br />";
echo
"HTTP_HOST : " . $_SERVER['HTTP_HOST'] . "<br />";
echo
"HTTP_REFERER : " . $_SERVER['HTTP_REFERER'] . "<br />";
echo
"HTTP_USER_AGENT : " . $_SERVER['HTTP_USER_AGENT'] . "<br />";
echo
"HTTPS : " . $_SERVER['HTTPS'] . "<br />";
echo
"REMOTE_ADDR : " . $_SERVER['REMOTE_ADDR'] . "<br />";
echo
"REMOTE_HOST : " . $_SERVER['REMOTE_HOST'] . "<br />";
echo
"REMOTE_PORT : " . $_SERVER['REMOTE_PORT'] . "<br />";
echo
"REMOTE_USER : " . $_SERVER['REMOTE_USER'] . "<br />";
echo
"REDIRECT_REMOTE_USER : " . $_SERVER['REDIRECT_REMOTE_USER'] . "<br />";
echo
"SCRIPT_FILENAME : " . $_SERVER['SCRIPT_FILENAME'] . "<br />";
echo
"SERVER_ADMIN : " . $_SERVER['SERVER_ADMIN'] . "<br />";
echo
"SERVER_PORT : " . $_SERVER['SERVER_PORT'] . "<br />";
echo
"SERVER_SIGNATURE : " . $_SERVER['SERVER_SIGNATURE'] . "<br />";
echo
"PATH_TRANSLATED : " . $_SERVER['PATH_TRANSLATED'] . "<br />";
echo
"SCRIPT_NAME : " . $_SERVER['SCRIPT_NAME'] . "<br />";
echo
"REQUEST_URI : " . $_SERVER['REQUEST_URI'] . "<br />";
echo
"PHP_AUTH_DIGEST : " . $_SERVER['PHP_AUTH_DIGEST'] . "<br />";
echo
"PHP_AUTH_USER : " . $_SERVER['PHP_AUTH_USER'] . "<br />";
echo
"PHP_AUTH_PW : " . $_SERVER['PHP_AUTH_PW'] . "<br />";
echo
"AUTH_TYPE : " . $_SERVER['AUTH_TYPE'] . "<br />";
echo
"PATH_INFO : " . $_SERVER['PATH_INFO'] . "<br />";
echo
"ORIG_PATH_INFO : " . $_SERVER['ORIG_PATH_INFO'] . "<br />";

?>

By : @44it

[EDITOR'S NOTE: Removed external link. EDITED BY: thiago]
up
8
steve at sc-fa dot com
5 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']
up
3
dtomasiewicz at gmail dot com
4 years ago
To get an associative array of HTTP request headers formatted similarly to get_headers(), this will do the trick:

<?php
/**
* Transforms $_SERVER HTTP headers into a nice associative array. For example:
*   array(
*       'Referer' => 'example.com',
*       'X-Requested-With' => 'XMLHttpRequest'
*   )
*/
function get_request_headers() {
   
$headers = array();
    foreach(
$_SERVER as $key => $value) {
        if(
strpos($key, 'HTTP_') === 0) {
           
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
        }
    }
    return
$headers;
}
?>
up
3
pomat at live dot it
1 year 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').
up
2
sendmailz1987 at gmail dot com
1 year ago
Example:

$current = $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];

echo $current;

will output the root to the current page, including url and document root, something like:

example.com/users/profile.php
up
3
jarrod at squarecrow dot com
5 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).
up
4
info at mtprod dot com
5 years ago
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
up
3
Tonin
6 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.
up
4
Tom
2 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.
up
4
wbeaumo1 at gmail dot com
4 years ago
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
up
4
php at isnoop dot net
4 years ago
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.

SetEnv varname "variable value"
up
5
pudding06 at gmail dot com
5 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.
up
3
Stefano (info at sarchittu dot org)
4 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.
up
3
admin at NOSpAM dot sinfocol dot org
4 years ago
I was testing with the $_SERVER variable and some request method, and I found that with apache I can put an arbitrary method.

For example, I have an script called "server.php" in my example webpage with the next code:

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

And I made this request:
c:\>nc -vv www.example.com 80
example.com [x.x.x.x] 80 (http) open
ArbitratyMethod /server.php HTTP/1.1
Host: wow.sinfocol.org
Connection: Close

The response of the server is the next:
HTTP/1.1 200 OK
Date: Fri, 15 Jan 2010 05:14:09 GMT
Server: Apache
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html

ArbitratyMethod

So, be carefully when include the $_SERVER['REQUEST_METHOD'] in any script, this kind of "bug" is old and could be dangerous.
up
2
dii3g0
2 years ago
Proccess path_info

<?php
function get_path_info()
{
    if( !
array_key_exists('PATH_INFO', $_SERVER) )
    {
       
$pos = strpos($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']);
   
       
$asd = substr($_SERVER['REQUEST_URI'], 0, $pos - 2);
       
$asd = substr($asd, strlen($_SERVER['SCRIPT_NAME']) + 1);
       
        return
$asd;   
    }
    else
    {
        return
trim($_SERVER['PATH_INFO'], '/');
    }
}
up
2
jette at nerdgirl dot dk
6 years ago
Windows running IIS v6 does not include $_SERVER['SERVER_ADDR']

If you need to get the IP addresse, use this instead:

<?php
$ipAddress
= gethostbyname($_SERVER['SERVER_NAME']);
?>
up
1
geoffrey dot hoffman at gmail dot com
6 years ago
If you are looking at $_SERVER['HTTP_USER_AGENT'] to determine whether your user is on a mobile device, you may want to visit these resources:

http://wurfl.sourceforge.net/

http://www.zytrax.com/tech/web/mobile_ids.html
up
1
kamazee at gmail dot com
4 years ago
$_SERVER['DOCUMENT_ROOT'] in different environments may has trailing slash or not, so be careful when including files from $_SERVER['DOCUMENT_ROOT']:
<?php
include(dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR . 'file.php')
?>
up
1
Gary Mathis
1 month ago
The best way to see all variables within the $_SERVER array, that I have found, is as follows:

<?php
foreach($_SERVER as $key => $value){
echo
'$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>

This will tell you which ones are available on your server and what they are set to.
up
0
softontherocks at gmail dot com
24 days ago
I want to share with you a full function to get the remote IP that calls a PHP url using the $_SERVER array.

function getRealIP(){
 if( $_SERVER['HTTP_X_FORWARDED_FOR'] != '' ){
  $client_ip =
   ( !empty($_SERVER['REMOTE_ADDR']) ) ?
    $_SERVER['REMOTE_ADDR']
   :
            ( ( !empty($_ENV['REMOTE_ADDR']) ) ?
    $_ENV['REMOTE_ADDR']
    :
    "unknown" );
 
  $entries = split('[, ]', $_SERVER['HTTP_X_FORWARDED_FOR']);
 
  reset($entries);
  while (list(, $entry) = each($entries)){
   $entry = trim($entry);
   if ( preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $entry, $ip_list) ){
    // http://www.faqs.org/rfcs/rfc1918.html
    $private_ip = array(
     '/^0\./',
     '/^127\.0\.0\.1/',
     '/^192\.168\..*/',
     '/^172\.((1[6-9])|(2[0-9])|(3[0-1]))\..*/',
     '/^10\..*/');
 
    $found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
 
    if ($client_ip != $found_ip){
     $client_ip = $found_ip;
     break;
    }
   }
  }
 } else {
  $client_ip =
   ( !empty($_SERVER['REMOTE_ADDR']) ) ?
    $_SERVER['REMOTE_ADDR']
   :
    ( ( !empty($_ENV['REMOTE_ADDR']) ) ?
    $_ENV['REMOTE_ADDR']
    :
    "unknown" );
 }
 return $client_ip;
}

This function was found in http://softontherocks.blogspot.com/2013/07/obtener-la-direccion-ip-que-solicita.html
up
0
Rodolfo Gonzalez Costa Rica
7 months ago
This is a short script to know what values are defined

<?php

echo "<textarea>";
print_r($_SERVER);
echo
"</textarea>";

?>
up
0
Dean Jenkins
1 year ago
To get the name and web path of the current script

<?php
$scriptname
=end(explode('/',$_SERVER['PHP_SELF']));
$scriptpath=str_replace($scriptname,'',$_SERVER['PHP_SELF']);
?>
up
-1
info at salientdigital dot com
10 months ago
A word of caution...

If you have some PHP code or file that is included from within a web request via Apache + PHP, as well as from a command line script, be very careful to inspect the keys inside of $_SERVER that you intend to use.

The keys and values are different, and in fact, it also matters if you are running as your_user, sudo php from your_user, or from root.

For example, I just found out that $_SERVER['PWD'] is not available if you run from the command line via sudo (PHP 5.2x, CentOS, YMMV).

To make a test, create a file called server.php with the following content:

<?php
var_dump
($_SERVER);
?>

Then from the commandline:
your_account/dir #$ php server.php > your_account_server.txt
your_account/dir #$ sudo php server.php > your_account_sudo_server.txt
your_account/dir #$ sudo bash
root/dir #$ php server.php > root_server.txt

Now you can diff the output of each of these three files and inspect against what you get when viewing the $_SERVER section of phpinfo() from a web request. You may find the differences to be quite striking, in all, four different ways to run the same PHP file!
up
-2
LOL
2 years ago
For an hosting that use windows I have used this script to make REQUEST_URI to be correctly setted on IIS
<?php
function request_URI() {
    if(!isset(
$_SERVER['REQUEST_URI'])) {
       
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
        if(
$_SERVER['QUERY_STRING']) {
           
$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
        }
    }
    return
$_SERVER['REQUEST_URI'];
}
$_SERVER['REQUEST_URI'] = request_URI();
?>
up
-2
Josh Fremer
3 years ago
HTTPS

Set to a non-empty value if the script was queried through the HTTPS protocol.

Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.

=-=-=

To clarify this, the value is the string "off", so a specific non-empty value rather than an empty value as in Apache.
up
-3
dragon[dot]dionysius[at]gmail[dot]com
5 years ago
I've updated the function of my previous poster and putted it into my class.

<?php
   
/**
     * Checking HTTP-Header for language
     * needed for various system classes
     *
     * @return    boolean    true/false
     */
   
private function _checkClientLanguage()
    {   
       
$langcode = (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
       
$langcode = (!empty($langcode)) ? explode(";", $langcode) : $langcode;
       
$langcode = (!empty($langcode['0'])) ? explode(",", $langcode['0']) : $langcode;
       
$langcode = (!empty($langcode['0'])) ? explode("-", $langcode['0']) : $langcode;
        return
$langcode['0'];
    }
?>

Please note, you have to check additional the result! Because the header may be missing or another possible thing, it is malformed. So check the result with a list with languages you support and perhaps you have to load a default language.

<?php

// if result isn't one of my defined languages
           
if(!in_array($lang, $language_list)) {
               
$lang = $language_default; // load default

?>

My HTTP_ACCEPT_LANGUAGE string:
FF3: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
IE7: de-ch

So, take care of it!
up
-3
Anonymous
4 years ago
Use Strict-Transport-Security (STS) to force the use of SSL.
<?php
$use_sts
= TRUE;

if (
$use_sts && isset($_SERVER['HTTPS']) {
 
header('Strict-Transport-Security: max-age=500');
} elseif (
$use_sts && !isset($_SERVER['HTTPS']) {
 
header('Status-Code: 301');
 
header('Location: https://'.$_SERVER["HTTP_HOST"].$_SERVER['REQUEST_URI']);
}
?>
up
-3
jeff at example dot com
6 years ago
Note that, in Apache 2, the server settings will affect the variables available in $_SERVER. For example, if you are using SSL, the following directive will dump SSL-related status information, along with the server certificate and client certificate (if present) into the $_SERVER variables:

SSLOptions +StdEnvVars +ExportCertData
up
-3
emailfire at gmail dot com
6 years ago
REQUEST_URI is useful, but if you want to get just the file name use:

<?php
$this_page
= basename($_SERVER['REQUEST_URI']);
if (
strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>
up
-3
picov at e-link dot it
3 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);
}
?>
up
-3
sabas88 at gmail dot com
1 year ago
I'm the author of this note
http://www.php.net/manual/en/reserved.variables.server.php#100881

I optimized since that note the path function, basically added detection of windows slashes and a partial option

Now is released on github

https://github.com/sabas/magicpath
up
-4
Taomyn
6 years ago
'HTTPS'
    Set to a non-empty value if the script was queried through the HTTPS protocol. Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.

Does the same for IIS7 running PHP as a Fast-CGI application.
up
-7
Andrew B
6 years ago
Please note on Windows/IIS - the variable 'USER_AUTH' will return the username/identity of the user accessing the page, i.e. if anonymous access is off, you would normally get back "$domain\$username".
up
-8
Megan Mickelson
4 years ago
It makes sense to want to paste the $_SERVER['REQUEST_URI'] on to a page (like on a footer), but be sure to clean it up first with htmlspecialchars() otherwise it poses a cross-site scripting vulnerability.

htmlspecialchars($_SERVER['REQUEST_URI']);

e.g.
http://www.example.com/foo?<script>...

becomes
http://www.example.com/foo?&lt;script&gt;...
up
-7
jit_chavan at yahoo dot com
9 months 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.
up
-3
derniereclasse at gmail dot com
9 months ago
About $_SERVER['REQUEST_METHOD']
return one of this values :
'GET', 'HEAD', 'POST', 'PUT'. 
but can also return :
'OPTION'
up
-15
Thomas Urban
6 years ago
Maybe you're missing information on $_SERVER['CONTENT_TYPE'] or $_SERVER['CONTENT_LENGTH'] as I did. On POST-requests these are available in addition to those listed above.
To Top