PHP
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

$_GET> <$GLOBALS
Last updated: Fri, 19 Jun 2009

view this page in

$_SERVER

$HTTP_SERVER_VARS [obsoleta]

$_SERVER -- $HTTP_SERVER_VARS [obsoleta]Información del servidor y el entorno de ejecución

Descripción

$_SERVER es una matriz que contiene información tal como cabeceras, rutas y ubicaciones de scripts. Las entradas de esta matriz son creadas por el servidor web. No existen garantías de que todo servidor vaya a proveer alguno de estos valores; puede que los servidores omitan algunos, o provean otros que no se listan aquí. Hecha esta aclaración, un gran número de estas variables hacen parte de la » especificación CGI 1.1, así que puede esperar que sean definidas por el servidor.

$HTTP_SERVER_VARS contiene la misma información inicial, pero no es una superglobal. (Note que $HTTP_SERVER_VARS y $_SERVER son variables diferentes y que PHP las trata como tal)

Pueden encontrarse o no cualquiera de los siguientes elementos en $_SERVER. Note que algunos pocos de éstos, si es que al menos uno de ellos, estarán disponibles (o tendrán algún significado real) si se ejecuta PHP en la línea de comandos.

'PHP_SELF'
El nombre de archivo del script ejecutándose actualmente, relativo a la raíz de documentos. Por ejemplo, $_SERVER['PHP_SELF'] en un script en la dirección http://example.com/test.php/foo.bar sería /test.php/foo.bar. La constante __FILE__ contiene la ruta completa y nombre del archivo actual (o en otras palabras, incluído). Si PHP está siendo ejecutado como un procesador de línea de comandos, esta variable contiene el nombre del script a partir de PHP 4.3.0. Anteriormente no estaba disponible.
'$argv'
Matriz de argumentos pasados al script. Cuando el script es ejecutado en la línea de comandos, ésta entrega acesso al estilo C a los parámetros de la línea de comandos. Cuando es llamado mediante el método GET, ésta contendrá la cadena de consulta (query).
'$argc'
Contiene el número de parámetros de línea de comandos pasados al script (si se ejecuta en la línea de comandos).
'GATEWAY_INTERFACE'
Qué revisión de la especificación CGI está usando el servidor; es decir 'CGI/1.1'.
'SERVER_ADDR'
La dirección IP del servidor bajo la cual está siendo ejecutado el script actual.
'SERVER_NAME'
El nombre del servidor anfitrión bajo el que está siendo ejecutado el script actual. Si el script está corriendo en un host virtual, éste será el valor definido para ese host virtual.
'SERVER_SOFTWARE'
Cadena de identificación del servidor, dada en las cabeceras cuando se responde a peticiones.
'SERVER_PROTOCOL'
Nombre y revisión del protocolo de información mediante el cual fue solicitada la página; es decir, 'HTTP/1.0';
'REQUEST_METHOD'
Cuál método de petición fue usado para acceder a la página; es decir, 'GET', 'HEAD', 'POST', 'PUT'.

Note: El script PHP es finalizado luego de enviar las cabeceras (es decir, después de producir cualquier salida sin uso de búferes de salida) si el método de petición fue HEAD.

'REQUEST_TIME'
La marca de tiempo del inicio de la petición. Disponible desde PHP 5.1.0.
'QUERY_STRING'
La cadena de consulta, si existe, mediante la cual se accedió a la página.
'DOCUMENT_ROOT'
El directorio raíz de documentos bajo el que está siendo ejecutado el script actual, tal y como se define en el archivo de configuración del servidor.
'HTTP_ACCEPT'
Contenidos de la cabecera Accept: de la petición actual, si existe.
'HTTP_ACCEPT_CHARSET'
Contenidos de la cabecera Accept-Charset: de la petición actual, si existe. Ejemplo: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contenidos de la cabecera Accept-Encoding: de la petición actual, si existe. Ejemplo: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contenidos de la cabecera Accept-Language: de la petición actual, si existe. Ejemplo: 'en'.
'HTTP_CONNECTION'
Contenidos de la cabecera Connection: de la petición actual, si existe. Ejemplo: 'Keep-Alive'.
'HTTP_HOST'
Contenidos de la cabecera Host: de la petición actual, si existe.
'HTTP_REFERER'
La dirección de la página (si la hay) la cual refirió al agente de usuario a la página actual. Este valor es definido por el agente de usuario. No todos los agentes de usuario lo definen, y algunos proveen la capacidad de modificar HTTP_REFERER como una característica del software. En resumen, no se puede confiar realmente en este valor.
'HTTP_USER_AGENT'
Contenidos de la cabecera User-Agent: de la petición actual, si existe. Esta es una cadena que denota el agente de usuario que está accediendo a la página. Un ejemplo típico es: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Entre otras cosas, puede usar este valor con get_browser() para personalizar la salida de su página a las capacidades del agente de usuario.
'HTTPS'
Definido con un valor no-vacío si el script fue solicitado a través del protocolo HTTPS. Note que cuando se usa ISAPI con IIS, el valor será off si la petición no fue hecha a través del protocolo HTTPS.
'REMOTE_ADDR'
La dirección IP desde donde el usuario está observado la página actual.
'REMOTE_HOST'
El nombre Host desde donde el usuario está viendo la página actual. La consulta dns de vuelta está basada en el valor REMOTE_ADDR del usuario.

Note: Su servidor web debe estar configurado para crear esta variable. Por ejemplo, en Apache necesitará HostnameLookups On dentro de httpd.conf para que exista. Vea también gethostbyaddr().

'REMOTE_PORT'
El puerto que está siendo usado en la máquina del usuario para comunicarse con el servidor web.
'SCRIPT_FILENAME'

La ruta absoluta del nombre del script siendo ejecutado actualmente.

Note: Si un script es ejecutado en el entorno CLI usando una ruta relativa, tal como archivo.php o ../archivo.php, $_SERVER['SCRIPT_FILENAME'] contendrá la ruta relativa especificada por el usuario.

'SERVER_ADMIN'
El valor dado a la directiva SERVER_ADMIN (para Apache) en el archivo de configuración del servidor web. Si el script está siendo ejecutado en un host virtual, éste será el valor definido para ese host virtual.
'SERVER_PORT'
El puerto en el equipo servidor que está siendo usado por el servidor web para comunicación. En configuraciones predeterminadas, ese valor será '80'; usando SSL, por ejemplo, este valor cambiará a cualquiera que sea el puerto que esté definido para HTTP seguro.
'SERVER_SIGNATURE'
Cadena que contiene la versión del servidor y el nombre de host virtual que es agregado a las páginas generadas por el servidor, si está habilitada esta funcionalidad.
'PATH_TRANSLATED'
Ruta sobre el sistema de archivos (no la raíz de documentos) al script actual, luego de que el servidor haya realizado cualquier asignación al vuelo virtual-a-real.

Note: A partir de PHP 4.3.2, PATH_TRANSLATED ya no se define implícitamente bajo la SAPI de Apache 2, a diferencia de lo que ocurre en Apache 1, en donde se define con el mismo valor de la variable de servidor SCRIPT_FILENAME cuando Apache no se encarga de definirlo. Este cambio fue realizado para cumplir con la especificación CGI de que PATH_TRANSLATED debe existir únicamente si PATH_INFO se define. Los usuarios de Apache 2 pueden usar AcceptPathInfo = On al interior de httpd.conf para definir PATH_INFO.

'SCRIPT_NAME'
Contiene la ruta del script actual. Ésta es útil para páginas que necesitan apuntar a ellas mismas. La constante __FILE__ contiene la ruta completa y nombre del archivo actual (es decir, incluido).
'REQUEST_URI'
El URI que fue dado para acceder a esta página; por ejemplo, '/index.html'.
'PHP_AUTH_DIGEST'
Cuando se está corriendo bajo Apache como módulo, realizando autenticación HTTP Digest, esta variable recibe el valor de la cabecera 'Authorization' enviada por el cliente (la cual debería ser usada para efectuar la validación apropiada).
'PHP_AUTH_USER'
Cuando se corre sobre Apache o IIS (ISAPI en PHP 5) como módulo realizando autenticación HTTP, esta variable es definida con el nombre de usuario definido por el cliente.
'PHP_AUTH_PW'
Cuando se corre sobre Apache o IIS (ISAPI en PHP 5) como módulo realizando autenticación HTTP, esta variable es definida con la contraseña entregada por el usuario.
'AUTH_TYPE'
Cuando se corre sobre Apache como módulo realizando autenticación HTTP, esta variable es definida con el tipo de autenticación.

Registro de cambios

Versión Descripción
4.1.0 Se introdujo $_SERVER, haciendo obsoleta a $HTTP_SERVER_VARS.

Ejemplos

Example #1 Ejemplo de $_SERVER

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

El resultado del ejemplo seria algo similar a:

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.

Ver también



$_GET> <$GLOBALS
Last updated: Fri, 19 Jun 2009
 
add a note add a note User Contributed Notes
$_SERVER
chris
02-Jul-2009 11:01
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
Myrddin
26-May-2009 06:00
To extend a bit on the table posted by jeffwk. You can use this piece of code to print all $_SERVER variables in a table with some mouse over effects to increase readability.

<?php
echo '<table style="border-collapse: collapse;">';
foreach (
$_SERVER as $key => $val)
    echo
'<tr onMouseOver="this.style.backgroundColor=\'AAAABB\';" onMouseOut="this.style.backgroundColor=\'transparent\';"><td style="font-weight: bold; border-right: 2px solid #000000;">'.$key.'</td><td style="width: 100%;">'.(is_array($val)?nl2br(print_r($val,true)):$val).'</td></tr>';
echo
'</table>';
?>
jeffwk
24-May-2009 11:43
Hi I made a table with all the $_SERVER['***'] calls listed here as per 24/05/09 - I needed some answers so I figured someone else may too.  Copy the following code in a .php file and run it on your server.
-------------------------------------------
<?php
echo "<table border=\"1\">";
echo
"<tr><td>" .$_SERVER['argv'] ."</td><td>argv</td></tr>";
echo
"<tr><td>" .$_SERVER['argc'] ."</td><td>argc</td></tr>";
echo
"<tr><td>" .$_SERVER['GATEWAY_INTERFACE'] ."</td><td>GATEWAY_INTERFACE</td></tr>";
echo
"<tr><td>" .$_SERVER['SERVER_ADDR'] ."</td><td>SERVER_ADDR</td></tr>";
echo
"<tr><td>" .$_SERVER['SERVER_NAME'] ."</td><td>SERVER_NAME</td></tr>";
echo
"<tr><td>" .$_SERVER['SERVER_SOFTWARE'] ."</td><td>SERVER_SOFTWARE</td></tr>";
echo
"<tr><td>" .$_SERVER['SERVER_PROTOCOL'] ."</td><td>SERVER_PROTOCOL</td></tr>";
echo
"<tr><td>" .$_SERVER['REQUEST_METHOD'] ."</td><td>REQUEST_METHOD</td></tr>";
echo
"<tr><td>" .$_SERVER['REQUEST_TIME'] ."</td><td>REQUEST_TIME</td></tr>";
echo
"<tr><td>" .$_SERVER['QUERY_STRING'] ."</td><td>QUERY_STRING</td></tr>";
echo
"<tr><td>" .$_SERVER['DOCUMENT_ROOT'] ."</td><td>DOCUMENT_ROOT</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTP_ACCEPT'] ."</td><td>HTTP_ACCEPT</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTP_ACCEPT_CHARSET'] ."</td><td>HTTP_ACCEPT_CHARSET</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTP_ACCEPT_ENCODING'] ."</td><td>HTTP_ACCEPT_ENCODING</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTP_ACCEPT_LANGUAGE'] ."</td><td>HTTP_ACCEPT_LANGUAGE</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTP_CONNECTION'] ."</td><td>HTTP_CONNECTION</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTP_HOST'] ."</td><td>HTTP_HOST</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTP_REFERER'] ."</td><td>HTTP_REFERER</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTP_USER_AGENT'] ."</td><td>HTTP_USER_AGENT</td></tr>";
echo
"<tr><td>" .$_SERVER['HTTPS'] ."</td><td>HTTPS</td></tr>";
echo
"<tr><td>" .$_SERVER['REMOTE_ADDR'] ."</td><td>REMOTE_ADDR</td></tr>";
echo
"<tr><td>" .$_SERVER['REMOTE_HOST'] ."</td><td>REMOTE_HOST</td></tr>";
echo
"<tr><td>" .$_SERVER['REMOTE_PORT'] ."</td><td>REMOTE_PORT</td></tr>";
echo
"<tr><td>" .$_SERVER['SCRIPT_FILENAME'] ."</td><td>SCRIPT_FILENAME</td></tr>";
echo
"<tr><td>" .$_SERVER['SERVER_ADMIN'] ."</td><td>SERVER_ADMIN</td></tr>";
echo
"<tr><td>" .$_SERVER['SERVER_PORT'] ."</td><td>SERVER_PORT</td></tr>";
echo
"<tr><td>" .$_SERVER['SERVER_SIGNATURE'] ."</td><td>SERVER_SIGNATURE</td></tr>";
echo
"<tr><td>" .$_SERVER['PATH_TRANSLATED'] ."</td><td>PATH_TRANSLATED</td></tr>";
echo
"<tr><td>" .$_SERVER['SCRIPT_NAME'] ."</td><td>SCRIPT_NAME</td></tr>";
echo
"<tr><td>" .$_SERVER['REQUEST_URI'] ."</td><td>REQUEST_URI</td></tr>";
echo
"<tr><td>" .$_SERVER['PHP_AUTH_DIGEST'] ."</td><td>PHP_AUTH_DIGEST</td></tr>";
echo
"<tr><td>" .$_SERVER['PHP_AUTH_USER'] ."</td><td>PHP_AUTH_USER</td></tr>";
echo
"<tr><td>" .$_SERVER['PHP_AUTH_PW'] ."</td><td>PHP_AUTH_PW</td></tr>";
echo
"<tr><td>" .$_SERVER['AUTH_TYPE'] ."</td><td>AUTH_TYPE</td></tr>";
echo
"</table>"
?>

---------------------------------------------------------------
pudding06 at gmail dot com
02-May-2009 09:44
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.
dragon[dot]dionysius[at]gmail[dot]com
29-Apr-2009 05:53
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!
dalys at chokladboll dot se
15-Apr-2009 09:03
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.";
?>
Vladimir Kornea
14-Mar-2009 01: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='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.
iosoft at gmail dot com
03-Mar-2009 05:11
This is a proper way to check for SSL -

<?php
function isSSL(){

  if(
$_SERVER['https'] == 1) /* Apache */ {
     return
TRUE;
  } elseif (
$_SERVER['https'] == 'on') /* IIS */ {
     return
TRUE;
  } elseif (
$_SERVER['SERVER_PORT'] == 443) /* others */ {
     return
TRUE;
  } else {
  return
FALSE; /* just using http */
 
}

}
?>
info at mtprod dot com
23-Jan-2009 10: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
24-Nov-2008 05: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

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.
jette at nerdgirl dot dk
01-Nov-2008 07:43
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']);
?>
geoffrey dot hoffman at gmail dot com
26-Oct-2008 12: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:

http://wurfl.sourceforge.net/

http://www.zytrax.com/tech/web/mobile_ids.html
Thomas Urban
22-Oct-2008 08: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 02:21
'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.
werner
08-Oct-2008 07:44
This is based on the post from 'emailfire at gmail dot com' (above)

If you only want to get the dir off the file you can use:

<?php
$this_dir
= $_SERVER['SCRIPT_FILENAME'];
if (
strpos($this_dir, basename($_SERVER['REQUEST_URI'])) !== false) $this_dir = reset(explode(basename($_SERVER['REQUEST_URI']), $this_dir));
echo
$this_dir;
?>
Tonin
16-Sep-2008 05: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 11: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 06: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
06-Aug-2008 12:55
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
danny at orionrobots dot co dot uk
31-Jul-2008 09: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 02:49
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));
?>

$_GET> <$GLOBALS
Last updated: Fri, 19 Jun 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites