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
$_SERVER
$HTTP_SERVER_VARS [Obsolète]
(PHP 4 >= 4.1.0, PHP 5)
$_SERVER -- $HTTP_SERVER_VARS [Obsolète] — Variables de serveur et d'exécution
Description
$_SERVER est un tableau contenant des informations comme les en-têtes, dossiers et chemins du script. Les entrées de ce tableau sont créées par le serveur web. Il n'y a aucune garantie que tous les serveurs les rempliront tous ; certains en oublieront quelques-unes et en rajouteront de nouvelles non mentionnées ici. Cependant, un grand nombre de ces variables fait partie des » spécifications CGI/1.1, et vous pouvez donc vous attendre à les retrouver.
$HTTP_SERVER_VARS contient les mêmes informations, mais n'est pas superglobale. (Notez que $HTTP_SERVER_VARS et $_SERVER sont des variables différentes et que PHP les traite en tant que telles.)
Indices
Vous pouvez éventuellement trouver les éléments suivants dans la variable $_SERVER. Notez que certains, n'auront pas de sens si vous utilisez PHP en ligne de commande.
- 'PHP_SELF'
- Le nom du fichier du script en cours d'exécution, par rapport à la racine web. Par exemple, $_SERVER['PHP_SELF'] dans le script situé à l'adresse http://www.monsite.com/test.php/foo.bar sera /test.php/foo.bar. La constante __FILE__ contient le chemin complet ainsi que le nom du fichier (i.e. inclus) courant. Si PHP fonctionne en ligne de commande, cette variable contient le nom du script depuis PHP 4.3.0. Dans les versions antérieures, cette variable n'était pas disponible.
- 'argv'
- Tableau des arguments passés au script. Lorsque le script est appelé en ligne de commande, cela donne accès aux arguments, comme en langage C. Lorsque le script est appelé avec la méthode GET, ce tableau contiendra la chaîne de requête.
- 'argc'
- Contient le nombre de paramètres de la ligne de commande passés au script (si le script fonctionne en ligne de commande).
- 'GATEWAY_INTERFACE'
- Numéro de révision de l'interface CGI du serveur : i.e. 'CGI/1.1'.
- 'SERVER_ADDR'
- L'adresse IP du serveur sous lequel le script courant est en train d'être exécuté.
- 'SERVER_NAME'
- Le nom du serveur hôte qui exécute le script suivant. Si le script est exécuté sur un hôte virtuel, ce sera la valeur définie pour cet hôte virtuel.
- 'SERVER_SOFTWARE'
- Chaîne d'identification du serveur, qui est donnée dans les en-têtes lors de la réponse aux requêtes.
- 'SERVER_PROTOCOL'
- Nom et révision du protocole de communication : i.e. 'HTTP/1.0';
- 'REQUEST_METHOD'
-
Méthode de requête utilisée pour accéder
à la page; i.e. 'GET',
'HEAD', 'POST', 'PUT'.
Note:
Le script PHP se termine après avoir envoyé les en-têtes (après avoir produit n'importe quelle sortie sans avoir affiché le buffer) si la méthode de la requête était HEAD.
- 'REQUEST_TIME'
- Le temps Unix du début de la requête. Disponible depuis PHP 5.1.0.
- 'REQUEST_TIME_FLOAT'
- Le timestamp du début de la requête, avec une précision à la microseconde. Disponible depuis PHP 5.4.0.
- 'QUERY_STRING'
- La chaîne de requête, si elle existe, qui est utilisée pour accéder à la page.
- 'DOCUMENT_ROOT'
- La racine sous laquelle le script courant est exécuté, comme défini dans la configuration du serveur.
- 'HTTP_ACCEPT'
- Contenu de l'en-tête Accept: de la requête courante, s'il y en a une.
- 'HTTP_ACCEPT_CHARSET'
- Contenu de l'en-tête Accept-Charset: de la requête courante, si elle existe. Par exemple : 'iso-8859-1,*,utf-8'.
- 'HTTP_ACCEPT_ENCODING'
- Contenu de l'en-tête Accept-Encoding: de la requête courante, si elle existe. Par exemple : 'gzip'.
- 'HTTP_ACCEPT_LANGUAGE'
- Contenu de l'en-tête Accept-Language: de la requête courante, si elle existe. Par exemple : 'fr'.
- 'HTTP_CONNECTION'
- Contenu de l'en-tête Connection: de la requête courante, si elle existe. Par exemple : 'Keep-Alive'.
- 'HTTP_HOST'
- Contenu de l'en-tête Host: de la requête courante, si elle existe.
- 'HTTP_REFERER'
- L'adresse de la page (si elle existe) qui a conduit le client à la page courante. Cette valeur est affectée par le client, et tous les clients ne le font pas. Certains navigateurs permettent même de modifier la valeur de HTTP_REFERER, sous forme de fonctionnalité. En bref, ce n'est pas une valeur de confiance.
- 'HTTP_USER_AGENT'
- Contenu de l'en-tête User_Agent: de la requête courante, si elle existe. C'est une chaîne qui décrit le client HTML utilisé pour voir la page courante. Par exemple : Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Entre autres choses, vous pouvez utiliser cette valeur avec get_browser() pour optimiser votre page en fonction des capacités du client.
- 'HTTPS'
-
Définissez à une valeur non-vide si le script nécessite d'utiliser le protocole HTTPS.
Note: Noter que lors de l'utilisation de ISAPI avec IIS, la valeur sera off si la demande n'a pas été faite via le protocole HTTPS.
- 'REMOTE_ADDR'
- L'adresse IP du client qui demande la page courante.
- 'REMOTE_HOST'
-
Le nom de l'hôte qui lit le script courant. La résolution
DNS inverse est basée sur la valeur de REMOTE_ADDR.
Note: Votre serveur web doit être configuré pour créer cette variable. Par exemple, pour Apache, vous devez ajouter la directive HostnameLookups On dans le fichier httpd.conf, pour que cette variable existe. Voyez aussi gethostbyaddr().
- 'REMOTE_PORT'
- Le port utilisé par la machine cliente pour communiquer avec le serveur web.
- 'REMOTE_USER'
- L'utilisateur authentifié.
- 'REDIRECT_REMOTE_USER'
- L'utilisateur authentifié si la requête a été redirigée en interne.
- 'SCRIPT_FILENAME'
-
Le chemin absolu vers le fichier contenant le script en cours d'exécution.
Note:
Si un script est exécuté avec le CLI, avec un chemin relatif, comme file.php ou ../file.php, $_SERVER['SCRIPT_FILENAME'] contiendra le chemin relatif spécifié par l'utilisateur.
- 'SERVER_ADMIN'
- La valeur donnée à la directive SERVER_ADMIN (pour Apache), dans le fichier de configuration. Si le script est exécuté par un hôte virtuel, ce sera la valeur définie par l'hôte virtuel.
- 'SERVER_PORT'
-
Le port de la machine serveur utilisé pour les
communications. Par défaut, c'est "80". En utilisant
SSL, par exemple, il sera remplacé par le numéro
de port HTTP sécurisé.
Note: Avec Apache 2, vous devez définir UseCanonicalName = On, mais aussi UseCanonicalPhysicalPort = On afin de récupérer le port physique (réel), sinon, cette valeur pourrait être erronée et pourrait retourner ou non la valeur correcte. Dans tous les cas, il n'est pas sécurisé que de faire confiance en cette valeur suivant le contexte.
- 'SERVER_SIGNATURE'
- Chaîne contenant le numéro de version du serveur et le nom d'hôte virtuel, qui sont ajoutés aux pages générées par le serveur, si cette option est activée.
- 'PATH_TRANSLATED'
-
Chemin dans le système de fichiers (pas le document-root)
jusqu'au script courant, une fois que le serveur a fait
une traduction chemin virtuel -> réel.
Note: Depuis PHP 4.3.2, la variable PATH_TRANSLATED n'est plus seulement définie implicitement sous Apache 2 SAPI contrairement à la situation sous Apache 1 où elle est définie avec la même valeur que la variable serveur SCRIPT_FILENAME lorsqu'elle n'est pas fournie par Apache. Ce changement a été effectué pour être conforme aux spécifications CGI qui fait que la variable PATH_TRANSLATED doit exister seulement si la variable PATH_INFO est définie. Les utilisateurs d'Apache 2 devraient utiliser AcceptPathInfo = On dans leur httpd.conf pour définir PATH_INFO.
- 'SCRIPT_NAME'
- Contient le nom du script courant. Cela sert lorsque les pages doivent s'appeler elles-mêmes. La constante __FILE__ contient le chemin complet ainsi que le nom du fichier (i.e. inclut) courant.
- 'REQUEST_URI'
- L'URI qui a été fourni pour accéder à cette page. Par exemple : '/index.html'.
- 'PHP_AUTH_DIGEST'
- Lorsque vous utilisez l'authentification HTTP Digest, cette variable est définie dans l'en-tête "Authorization" envoyé par le client (que vous devez donc utiliser pour réaliser la validation appropriée).
- 'PHP_AUTH_USER'
- Lorsque vous utilisez l'authentification HTTP, cette variable est définie à l'utilisateur fourni par l'utilisateur.
- 'PHP_AUTH_PW'
- Lorsque vous utilisez l'authentification HTTP, cette variable est définie au mot de passe fourni par l'utilisateur.
- 'AUTH_TYPE'
- Lorsque vous utilisez l'authentification HTTP, cette variable est définie au type d'identification.
- 'PATH_INFO'
- Contient les informations sur le nom du chemin fourni par le client concernant le nom du fichier exécutant le script courant, sans la chaîne relative à la requête si elle existe. Actuellement, si le script courant est exécuté via l'URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, alors la variable $_SERVER['PATH_INFO'] contiendra /some/stuff.
- 'ORIG_PATH_INFO'
- Version orignale de 'PATH_INFO' avant d'être analysée par PHP.
Historique
| Version | Description |
|---|---|
| 4.1.0 | Introduction de $_SERVER, rendant obsolète $HTTP_SERVER_VARS. |
Exemples
Exemple #1 Exemple avec $_SERVER
<?php
echo $_SERVER['SERVER_NAME'];
?>
L'exemple ci-dessus va afficher quelque chose de similaire à :
www.example.com
Notes
Note:
Ceci est une 'superglobale', ou variable globale automatique. Cela signifie simplement que cette variable est disponible dans tous les contextes du script. Il n'est pas nécessaire de faire global $variable; pour y accéder dans les fonctions ou les méthodes.
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']);
?>
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
<?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
)
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.
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.
SetEnv varname "variable value"
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.
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']
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'], '/');
}
}
$_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')
?>
'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.
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.
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";}
?>
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
}
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.
$_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).
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)
}
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.
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 -
*/
?>
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
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();
?>
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/includeFile.inc.php)
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 http://php.about.com/od/learnphp/qt/_SERVER_PHP.htm for tests.
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.
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.
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;
}
?>
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
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.
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!
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
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']);
?>
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
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
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));
?>
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);
}
?>
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.
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']);
}
?>
$_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.
There are two different variables that I find very useful in Caching and similar.
$_SERVER['REQUEST_URI'] and $_SERVER['REQUEST_URL']
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.
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?<script>...
If you want en, sv-SE, da, es etc. to be returned from $_SERVER['HTTP_ACCEPT_LANGUAGE'] you can use this function:
<?php
function detectlanguage() {
$langcode = explode(";", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$langcode = explode(",", $langcode['0']);
return $langcode['0'];
}
$language = detectlanguage();
echo "You have chosen $language as your language in your web browser.";
?>
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.
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".
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
It is worth noting here that if you use $_SERVER['REQUEST_URI'] with a rewrite rule, the original, not rewritten URI will be presented.
$_SERVER["SCRIPT_FILENAME"] returns the path including the filename, like __DIR__
