The Server Pages
:: TSP Menu
- Home
- Authors
- Glossary
- RSS Feed

:: Servers
- CPanel
- Hosting
- Linux
- Windows

:: Webmaster
- Databases
- Design
- Search Engines

:: Scripts
- Scripts

:: Documentation
- PHP Manual

:: Other
- Errors & Solutions
- TechPunt
- Wojjie

search for in the

[edit] Last updated: Sat, 12 May 2012

view this page in


$HTTP_SERVER_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_SERVER -- $HTTP_SERVER_VARS [deprecated]Server and execution environment information


$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)


You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address would be /test.php/ The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
Contains the number of command line parameters passed to the script (if run on the command line).
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
The IP address of the server under which the current script is executing.
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
Server identification string, given in the headers when responding to requests.
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.


PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

The timestamp of the start of the request. Available since PHP 5.1.0.
The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0.
The query string, if any, via which the page was accessed.
The document root directory under which the current script is executing, as defined in the server's configuration file.
Contents of the Accept: header from the current request, if there is one.
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
Contents of the Host: header from the current request, if there is one.
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
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.

The IP address from which the user is viewing the current page.
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

The port being used on the user's machine to communicate with the web server.
The authenticated user.
The authenticated user if the request is internally redirected.

The absolute pathname of the currently executing script.


If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
The URI which was given in order to access this page; for instance, '/index.html'.
When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
When doing HTTP authentication this variable is set to the username provided by the user.
When doing HTTP authentication this variable is set to the password provided by the user.
When doing HTTP authenticated this variable is set to the authentication type.
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL, then $_SERVER['PATH_INFO'] would contain /some/stuff.
Original version of 'PATH_INFO' before processed by PHP.


Version Description
4.1.0 Introduced $_SERVER that deprecated $HTTP_SERVER_VARS.


Example #1 $_SERVER example


The above example will output something similar to:



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.

[edit] Last updated: Sat, 12 May 2012
add a note add a note User Contributed Notes $_SERVER
dii3g0 17-Apr-2012 04:43
Proccess path_info

function get_path_info()
    if( !
array_key_exists('PATH_INFO', $_SERVER) )
$asd = substr($_SERVER['REQUEST_URI'], 0, $pos - 2);
$asd = substr($asd, strlen($_SERVER['SCRIPT_NAME']) + 1);
trim($_SERVER['PATH_INFO'], '/');
LOL 05-Apr-2012 01:26
For an hosting that use windows I have used this script to make REQUEST_URI to be correctly setted on IIS
function request_URI() {
$_SERVER['REQUEST_URI'] = request_URI();
mdlamar at gmail dot com 12-Dec-2011 03:04
$_SERVER['SERVER_ADDR'] contains my LAN IP rather than the public IP. I used the function gethostbyname() to get my public IP rather than the router assigned local IP.
picov at e-link dot it 13-Oct-2011 10:59
A simple function to detect if the current page address was rewritten by mod_rewrite:

public function urlWasRewritten() {
$virtualScriptName=reset(explode("?", $_SERVER['REQUEST_URI']));
  return !(
MarkAgius at markagius dot co dot uk 31-Aug-2011 02:18
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
$HttpStatus==200) {print "Document has been processed and sent to you.";}
$HttpStatus==400) {print "Bad HTTP request ";}
$HttpStatus==401) {print "Unauthorized - Iinvalid password";}
$HttpStatus==403) {print "Forbidden";}
$HttpStatus==500) {print "Internal Server Error";}
$HttpStatus==418) {print "I'm a teapot! - This is a real value, defined in 1998";}

Jamie 02-Mar-2011 01:18
Note that on real paths, aliases are not resolved

$_SERVER["DOCUMENT_ROOT"] => /var/services/web/mysite
$_SERVER["SCRIPT_FILENAME"] => /var/services/web/mysite/admin/products.php

(but __FILE__ => /volume1/web/mysite/admin/inc/
Use realpath to resolve the $_SERVER value.

Virtual paths also have some differences:
$_SERVER["SCRIPT_NAME"] => /admin/products.php (virtual path)
$_SERVER["PHP_SELF"] => /admin/products.php/someExtraStuff (virtual path)

SCRIPT_NAME is defined in the CGI 1.1 specification, PHP_SELF is created by PHP itself. See for tests.
sainthyoga2003 at gmail dot com 25-Feb-2011 12:37
$_SERVER["SCRIPT_FILENAME"] returns the path including the filename, like __DIR__
Josh Fremer 20-Dec-2010 10:47

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.
rulerof at gmail dot com 17-Nov-2010 10:12
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:

function GetBasePath() {
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.
Stefano (info at sarchittu dot org) 12-Nov-2010 06:07
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


$host will finally contain the absolute path.
Anonymous 12-Nov-2010 04:22
Use Strict-Transport-Security (STS) to force the use of SSL.

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']);
dtomasiewicz at gmail dot com 14-Aug-2010 08:03
To get an associative array of HTTP request headers formatted similarly to get_headers(), this will do the trick:

 * Transforms $_SERVER HTTP headers into a nice associative array. For example:
 *   array(
 *       'Referer' => '',
 *       'X-Requested-With' => 'XMLHttpRequest'
 *   )
function get_request_headers() {
$headers = array();
$_SERVER as $key => $value) {
strpos($key, 'HTTP_') === 0) {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
wbeaumo1 at gmail dot com 13-Jun-2010 08:43
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
kamazee at gmail dot com 15-Apr-2010 06:41
$_SERVER['DOCUMENT_ROOT'] in different environments may has trailing slash or not, so be careful when including files from $_SERVER['DOCUMENT_ROOT']:
include(dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR . 'file.php')
php at isnoop dot net 01-Apr-2010 09:38
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.

SetEnv varname "variable value"
piana at pyrohawk dot com 17-Mar-2010 09:26
There are two different variables that I find very useful in Caching and similar.


URI provides the entire request path (/directory/file.ext?query=string)
URL provides the request path, without the query string (/directory/file.ext)
It also differs from __FILE__ in that it's not the file name.  So, if you go to /directory/anotherfile.ext and get silently redirected to file.ext, these variables are anotherfile.ext, while __FILE__ is still file.ext.
Megan Mickelson 22-Feb-2010 03:36
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.



admin at NOSpAM dot sinfocol dot org 14-Jan-2010 10:31
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:


And I made this request:
c:\>nc -vv 80 [x.x.x.x] 80 (http) open
ArbitratyMethod /server.php HTTP/1.1
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


So, be carefully when include the $_SERVER['REQUEST_METHOD'] in any script, this kind of "bug" is old and could be dangerous.
mirko dot steiner at slashdevslashnull dot de 24-Oct-2009 02:43

// RFC 2616 compatible Accept Language Parser
//, 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})'.

$splits = array();

printf("Lang:,,%s''\n", $lang);
    if (
preg_match($pattern, $lang, $splits)) {
    } else {
"\nno match\n";


example output:

Google Chrome Windows xp

    [0] => de-DE
    [primarytag] => de
    [1] => de
    [subtag] => DE
    [2] => DE
    [0] => de;q=0.8
    [primarytag] => de
    [1] => de
    [subtag] =>
    [2] =>
    [quantifier] => 0.8
    [3] => 0.8
    [0] => en-US;q=0.6
    [primarytag] => en
    [1] => en
    [subtag] => US
    [2] => US
    [quantifier] => 0.6
    [3] => 0.6
    [0] => en;q=0.4
    [primarytag] => en
    [1] => en
    [subtag] =>
    [2] =>
    [quantifier] => 0.4
    [3] => 0.4
Lord Mac 14-Oct-2009 07:56
An even *more* improved version...

steve at sc-fa dot com 17-Sep-2009 12:20
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_SERVER'] in place of (at least in our case,) $_SERVER['SERVER_NAME']
cupy at email dot cz 20-Aug-2009 08:24
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:

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];
   {        // default
     $EID = 0x0210; // PPS failure
jarrod at squarecrow dot com 10-Aug-2009 08:31
$_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:

//Defines constants to use for "include" URLS - helps keep our paths clean


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).
Richard York 09-Jul-2009 11:19
Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell.

  array(24) {
    string(48) "/usr/share/man:/usr/local/share/man:/usr/X11/man"
    string(11) "xterm-color"
    string(9) "/bin/bash"
    string(20) " 41242 22"
    string(60) "/Library/WebServer/Domains/"
    string(12) "/dev/ttys000"
    string(5) "username"
    string(15) "/var/mail/username"
    string(57) "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin"
    string(56) "/Library/WebServer/Domains/"
    string(1) "1"
    string(12) "/Users/username"
    string(5) "username"
    string(31) " 41242 22"
    string(12) "/usr/bin/php"
    string(9) "0x1F5:0:0"
    string(10) "Shell.php"
    string(10) "Shell.php"
    string(10) "Shell.php"
    string(10) "Shell.php"
    string(0) ""
    array(1) {
      string(10) "Shell.php"
chris 02-Jul-2009 04:01
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
pudding06 at gmail dot com 02-May-2009 02:44
Here's a simple, quick but effective way to block unwanted external visitors to your local server:

// only local requests
if ($_SERVER['REMOTE_ADDR'] !== '') 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.
dragon[dot]dionysius[at]gmail[dot]com 29-Apr-2009 10:53
I've updated the function of my previous poster and putted it into my class.

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

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.


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


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

So, take care of it!
dalys at chokladboll dot se 15-Apr-2009 02:03
If you want en, sv-SE, da, es etc. to be returned from $_SERVER['HTTP_ACCEPT_LANGUAGE'] you can use this function:

function detectlanguage() {
$langcode = explode(";", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$langcode = explode(",", $langcode['0']);

$language = detectlanguage();

"You have chosen $language as your language in your web browser.";
Vladimir Kornea 13-Mar-2009 05:06
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='"><script type="text/javascript">...</script><span a="'></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.
info at mtprod dot com 23-Jan-2009 02:13
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
jonbarnett at gmail dot com 23-Nov-2008 09:13
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


['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.
jette at nerdgirl dot dk 01-Nov-2008 11:43
Windows running IIS v6 does not include $_SERVER['SERVER_ADDR']

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

= gethostbyname($_SERVER['SERVER_NAME']);
geoffrey dot hoffman at gmail dot com 25-Oct-2008 05:13
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:
Thomas Urban 22-Oct-2008 01:19
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.
Taomyn 12-Oct-2008 07:21
    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.
Tonin 16-Sep-2008 10:43
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.
Andrew B 08-Sep-2008 04:26
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".
jeff at example dot com 12-Aug-2008 11:24
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
silverquick at gmail dot com 05-Aug-2008 05:55
I think the HTTPS element will only be present under Apache 2.x. It's not in the list of "special" variables here:
But it is here:
danny at orionrobots dot co dot uk 31-Jul-2008 02:25
It is worth noting here that if you use $_SERVER['REQUEST_URI'] with a rewrite rule, the original, not rewritten URI will be presented.
emailfire at gmail dot com 26-May-2008 07:49
REQUEST_URI is useful, but if you want to get just the file name use:

= basename($_SERVER['REQUEST_URI']);
if (
strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));

show source | credits | sitemap | contact | advertising | mirror sites