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

search for in the

Clases Predefinidas> <Lista de Palabras Reservadas
Last updated: Tue, 27 Nov 2007

view this page in

Variables Predefinidas

A partir de PHP 4.1.0, el método preferido para recuperar variables externas es mediante las superglobales mencionadas más adelante. Antes de este punto, la gente recaía en register_globals o las matrices largas predefinidas en PHP ($HTTP_*_VARS). A partir de PHP 5.0.0, las matrices de tipo "long" de variables predefinidas, se pueden desactivar con la directiva register_long_arrays.

Variables de servidor: $_SERVER

Note: Aparecieron en 4.1.0. En versiones anteriores, utilice $HTTP_SERVER_VARS.

$_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 cada 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.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo de un script. No necesita hacer global $_SERVER; para acceder a ella dentro de funciones o métodos, como lo hace con $HTTP_SERVER_VARS.

$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)

Si la directiva register_globals está definida, entonces estas variables también estarán disponibles en el contexto global del script; esto quiere decir, por separado de las matrices $_SERVER y $HTTP_SERVER_VARS. Para información relacionada, vea el capítulo de seguridad titulado Uso de Registros Globales. Estas variables globales individuales no son superglobales.

Usted puede encontrar o no cualquiera de los siguientes elementos en $_SERVER. Note que algunos de éstos, si es que los hay, estarán disponibles (o tendrán algún significado después de todo) 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 (es decir, incluido). 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 tal 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.

Variables de entorno: $_ENV

Note: Introducidas en 4.1.0. En versiones anteriores, use $HTTP_ENV_VARS.

Estas variables son importadas en el espacio de nombres global de PHP desde el entorno bajo el que está siendo ejecutado el intérprete PHP. Muchas son entregadas por el intérprete de comandos bajo el que PHP está corriendo y diferentes sistemas suelen tener diferentes tipos de intérpretes de comandos, una lista definitiva es imposible. Por favor consulte la documentación de su intérprete de comandos por una lista de varibles de entorno que resultan definidas.

Otras variables de entorno incluyen las variables CGI, colocadas allí independientemente de que PHP esté siendo ejecutado como módulo del servidor o procesador CGI.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo del script. No necesita hacer global $_ENV; para acceder a ella desde funciones o métodos, tal y como lo hace con $HTTP_ENV_VARS.

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

Si la directiva register_globals está definida, entonces estas variables también se harán disponibles en el entorno global del script; i.e., por separado de las matrices $_ENV y $HTTP_ENV_VARS. Para información relacionada, consulte el capítulo de seguridad titulado Uso de Registros Globales. Estas globales individuales no son superglobales.

Cookies HTTP: $_COOKIE

Note: Introducidas en 4.1.0. En versiones anteriores, use $HTTP_COOKIE_VARS.

Una matriz asociativa de variables pasadas al script actual a través de cookies HTTP. Global automáticamente en cualquier contexto.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo de un script. No necesita hacer global $_COOKIE; para acceder a ella dentro de funciones o métodos, como lo hace con $HTTP_COOKIE_VARS.

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

Si la directiva register_globals está definida, entonces estas variables también estarán disponibles en el contexto global del script; i.e., por separado de las matrices $_COOKIE y $HTTP_COOKIE_VARS. Para información relacionada, consulte el capítulo de seguridad titulado Uso de Registros Globales. Estas globales individuales no son superglobales.

Variables HTTP GET: $_GET

Note: Introducidas en 4.1.0. En versiones anteriores, use $HTTP_GET_VARS.

Una matriz asociativa de variables pasadas al script actual a través del método HTTP GET. Global automáticamente en cualquier contexto.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo de un script. No necesita hacer global $_GET; para acceder a ella dentro de funciones o métodos, como lo hace con $HTTP_GET_VARS.

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

Si la directiva register_globals está definida, entonces estas variables también estarán disponibles en el contexto global del script; i.e., por separado de las matrices $_GET y $HTTP_GET_VARS. Para información relacionada, consulte el capítulo de seguridad titulado Uso de Registros Globales. Estas globales individuales no son superglobales.

Variables HTTP POST: $_POST

Note: Introducidas en 4.1.0. En versiones anteriores, use $HTTP_POST_VARS.

Una matriz asociativa de variables pasadas al script actual a través del método HTTP POST. Global automáticamente en cualquier contexto.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo de un script. No necesita hacer global $_POST; para acceder a ella dentro de funciones o métodos, como lo hace con $HTTP_POST_VARS.

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

Si la directiva register_globals está definida, entonces estas variables también estarán disponibles en el contexto global del script; i.e., por separado de las matrices $_POST y $HTTP_POST_VARS. Para información relacionada, consulte el capítulo de seguridad titulado Uso de Registros Globales. Estas globales individuales no son superglobales.

Variables de carga de archivos HTTP: $_FILES

Note: Introducidas en 4.1.0. En versiones anteriores, use $HTTP_POST_FILES.

Una matriz asociativa de elementos cargados al script actual a través del método HTTP POST. Global automáticamente en cualquier contexto.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo de un script. No necesita hacer global $_FILES; para acceder a ella dentro de funciones o métodos, como lo hace con $HTTP_POST_FILES.

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

Si la directiva register_globals está definida, entonces estas variables también estarán disponibles en el contexto global del script; i.e., por separado de las matrices $_FILES y $HTTP_POST_FILES. Para información relacionada, consulte el capítulo de seguridad titulado Uso de Registros Globales. Estas globales individuales no son superglobales.

Variables de petición: $_REQUEST

Note: Introducidas en 4.1.0. No existe una matriz equivalente en versiones anteriores.

Note: Antes de PHP 4.3.0, la información de $_FILES también era incluida en $_REQUEST.

Una matriz asociativa que consiste en los contenidos de $_GET, $_POST, y $_COOKIE.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo de un script. No necesita hacer global $_REQUEST; para acceder a ella dentro de funciones o métodos.

Si la directiva register_globals está definida, entonces estas variables también estarán disponibles en el contexto global del script; i.e., por separado de la matriz $_REQUEST. Para información relacionada, consulte el capítulo de seguridad titulado Uso de Registros Globales. Estas globales individuales no son superglobales.

Variables de sesión: $_SESSION

Note: Introducidas en 4.1.0. En versiones anteriores, use $HTTP_SESSION_VARS.

Una matriz asociativa que contiene las variables de sesión disponibles en el script actual. Consulte la documentación sobre Funciones de Sesión para más información sobre cómo es usada esta matriz.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo de un script. No necesita hacer global $_SESSION; para acceder a ella dentro de funciones o métodos, como lo hace con $HTTP_SESSION_VARS.

$HTTP_SESSION_VARS contiene la misma información, pero no es una superglobal. (Note que $HTTP_SESSION_VARS y $_SESSION son variable diferentes y que PHP las trata como tal)

Si la directiva register_globals está definida, entonces estas variables también estarán disponibles en el contexto global del script; i.e., por separado de las matrices $_SESSION y $HTTP_SESSION_VARS. Para información relacionada, consulte el capítulo de seguridad titulado Uso de Registros Globales. Estas globales individuales no son superglobales.

Variables globales: $GLOBALS

Note: $GLOBALS ha estado disponible desde PHP 3.0.0.

Una matriz asociativa que contiene referencias a todas las variables que están definidas actualmente en el contexto global del script. Los nombres de las variables son las claves de la matriz.

Esta es una variable 'superglobal', o global automática. Esto simplemente quiere decir que está disponible en todos los contextos a lo largo de un script. No necesita hacer global $_GLOBALS; para acceder a ella dentro de funciones o métodos.

El mensaje de error previo: $php_errormsg

$php_errormsg es una variable que contiene el texto del último mensaje de error generado por PHP. Esta variable solo estará disponibles dentro del contexto en el que el error ocurrió, y solo si la opción de configuración track_errors está habilitada (por omisión está definida como off).

Datos POST puros: $HTTP_RAW_POST_DATA

$HTTP_RAW_POST_DATA contiene los datos POST inalterados. Vea always_populate_raw_post_data

Cabeceras de respuesta HTTP: $http_response_header

La matriz $http_response_header es similar a la función get_headers(). Cuando se usa la envoltura HTTP $http_response_header será populada con las cabeceras de respuesta HTTP.



Clases Predefinidas> <Lista de Palabras Reservadas
Last updated: Tue, 27 Nov 2007
 
add a note add a note User Contributed Notes
Variables Predefinidas
Nicolae Namolovan
22-Nov-2007 09:49
SECURITY RISK !

Never ever trust the values that comes from $_SERVER.

HTTP_X_FORWARDED, HTTP_X_FORWARDED_FOR, HTTP_FORWARDED_FOR, HTTP_FORWARDED, etc.. can be spoofed !

To get the ip of user, use only $_SERVER['REMOTE_ADDR'], otherwise the 'ip' of user can be easily changed by sending a HTTP_X_* header, so user can escape a ban or spoof a trusted ip.

Of course this is well know, but I don't see it mentioned in these notes..

If you use the ip only for tracking (not for any security features like banning or allow access to something by ip), you can also use HTTP_X_FORWARDED to get user's ip what are behind proxy.
new to PHP, old hand at C
16-Nov-2007 11:44
Here is an ever-so-slightly more efficient version of Dlyaza's code snippet to get an IP address.  I think this ought to work, and if so, it should produce the same results as her original snippet below.

<?php
   
if ($IP = getenv('HTTP_CLIENT_IP')) {}
      elseif (
$IP = getenv('HTTP_X_FORWARDED_FOR')) {}
      elseif (
$IP = getenv('HTTP_X_FORWARDED')) {}
      elseif (
$IP = getenv('HTTP_FORWARDED_FOR')) {}
      elseif (
$IP = getenv('HTTP_FORWARDED')) {}
      else {
       
$IP = $_SERVER['REMOTE_ADDR'];
    }
?>
crescentfreshpot at yahoo dot com
14-Nov-2007 08:03
In response to mathiasrav's getip() implementation on 28-Jul-2007, it should be noted that it:

- assumes IPv4 addresses only
- returns $_SERVER['REMOTE_ADDR'] for any value of $_SERVER['HTTP_CLIENT_IP'] that matches 127.0.*.*, 192.168.*.* or 10.0.*.*, which is not desirable if you actually WANT the value of HTTP_CLIENT_IP

dlyaza's prior snippet has neither of these problems.
martin dot szwarc at gmail dot com
02-Nov-2007 05:40
For a pretty browser name:

if (stristr($_SERVER['HTTP_USER_AGENT'],"firefox")) {
$agent = "Firefox";
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'],"safari")) {
$agent = "Safari";
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'],"msie 7")) {
$agent = "IE 7";
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'],"opera")) {
$agent = "Opera";
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'],"msie 6")) {
$agent = "IE 6";
}
else {
$agent = "UNKNOWN";
}
root at mantoru dot de
01-Nov-2007 04:59
Note that some headers will be checked for validity (by Apache, I suppose) before showing up in $_SERVER -- If-Modified-Since for example.

<?php
$lastmod
= gmdate('D, d M Y H:i:s', filemtime('somefile'));
header("Last-Modified: $lastmod");
?>

This WON'T work, "GMT" is missing. Internet Explorer auto-fixes this by adding GMT, while Firefox resends this data as-is. (So an If-Modified-Since-header is sent, but neither shows up in $_SERVER nor in apache_request_headers()). This would be correct:

<?php
$lastmod
= gmdate('D, d M Y H:i:s', filemtime('somefile')) . 'GMT';
header("Last-Modified: $lastmod");
?>
jsan
19-Oct-2007 09:39
@White-Gandalf: one can control this behavior by setting:

UseCanonicalName On|Off

in their apache config (at least, on *ix platforms).

On => $_SERVER['SERVER_NAME'] is the ServerName var from either the global server or virtual host, whichever wraps the PHP app closest.

Off => Whatever was in the Host: header sent by the client.
White-Gandalf
16-Oct-2007 04:01
'SERVER_NAME' does NOT necessarily refer to the name of a virtual host or any other things defined in the apache config.
Instead it simply takes the value of the "Host:" entry of the HTTP-header sent by the client.
At least with apache version 2.2.5 on Windows.
doheth.co.uk
14-Oct-2007 01:15
slight improvement to the example by 'andres at andresj dot ath dot cx' for determining the path to the currently script.

Previous version:

<?php
// If your script is included from another script:
$included_directory = substr(__FILE__, 0, strrpos(__FILE__, '/'));
?>

Windows uses back-slash to indicate folders, so this didn't work on localhost for me. All you need to do is convert any back-slashes to forward-slashes. This should work on all systems:

<?php
// If your script is included from another script:
$included_file = str_replace('\\', '/', __FILE__);
$included_directory = substr($included_file, 0, strrpos($included_file, '/'));
?>
Error Code
05-Oct-2007 10:30
An easy coding, but usefull

<?
$agent      
= $_SERVER['HTTP_USER_AGENT'];
$ip          = $_SERVER['REMOTE_ADDR'];
$port        = $_SERVER['REMOTE_PORT'];
$d           = date ('dS \of F Y h:1:s A');

echo
"Your IP : $ip<br>";
echo
"You are using : $agent<br>";
echo
"You are connected thruogh port : $port<br>";
echo
"Today is : $d";

$fp = fopen("data", "a");
fwrite($fp, "\n");
fwrite($fp, "\n");
fwrite($fp, "\n");
fwrite($fp, "Your IP : $ip");
fwrite($fp, "\n");
fwrite($fp, "You are using : $agent");
fwrite($fp, "\n");
fwrite($fp, "You are connected thruogh port : $port");
fwrite($fp, "\n");
fwrite($fp, "Today is : $d");
fwrite($fp, "\n");
fwrite($fp, "***********________________***********");

?>

it can show these information in your page and it saves it
you can also hide these info by removing

echo "Your IP : $ip<br>";
echo "You are using : $agent<br>";
echo "You are connected thruogh port : $port<br>";
echo "Today is : $d";

or you can change the coding and let it save the info in the database mysql_connect (
cancausecancerr at yahoo dot com dot cn
01-Oct-2007 11:23
The setGetVar() function posted above has an error in it. If $var exists in the path but not as a variable then the URI is returned unaltered:

Example:
URI=http://localhost/images/upload/image.php?page=1403
setGetVar('image','40')

'image' is found by strstr($request_uri, $var) but since its not in the variables;  preg_replace returns the original uri.

<?php
function setGetVar($var, $val){
   
$request_uri = $_SERVER["REQUEST_URI"];
    if(
strstr($request_uri, $var)) {
        return
preg_replace("/$var=[\\d\\w]*/", "$var=$val", $request_uri);
    } elseif(
strstr($request_uri, "?")) {
        return
$request_uri . "&" . $var . "=" . $val;
    } else {
        return
$request_uri . "?" . $var . "=" . $val;
    }
}
?>

This is the fixed copy of the function. If $var is found then the preg_replace is executed but this time the result URI is compared against the initial URI. If they are the same then $var wasn't replaced and the script continues on to append it to the URI.

<?php
function setGetVar($var, $val) {
   
$request_uri = $_SERVER["REQUEST_URI"];
    if (
strstr($request_uri, $var)) {
           
$newURI = preg_replace("/$var=[\\d\\w]*/", "s$var=$val", $request_uri);
        if (
$newURI != $request_uri) return $newURI;
    }
    if (
strstr($request_uri, "?")) return $request_uri . "&" . $var . "=" . $val;
    else return
$request_uri . "?" . $var . "=" . $val;
}
?>
phpnotes dot 20 dot zsh at spamgourmet dot com
21-Sep-2007 05:45
The headers sent by the browser will be stored in the $_SERVER array -- they will get capitalized and prefixed with HTTP. So a header like "X-Foo-Bar: Baz" will result in <?php $_SERVER['HTTP_X_FOO_BAR'] = 'Baz';?>. This is why you should use isset before using e.g. HTTP_ACCEPT_LANGUAGE, 'cause it may not be set.

The only exception I know from that is HTTP_X_ORIGINAL_URI, which is always set and holds the current URL without querystring. But you can't trust that too because it can be overriden by sending a X-Original-URI header.
anonymous
10-Aug-2007 06:48
To get the filename use:

basename($_SERVER['SCRIPT_FILENAME'])
andres at andresj dot ath dot cx
05-Aug-2007 07:41
To get the directory of the current script: (I think this is a little more resource-friendly, but then again with all the fast computers available, it does not matter so much...)
<?
// For the script that is running:
$script_directory = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], '/'));
// If your script is included from another script:
$included_directory = substr(__FILE__, 0, strrpos(__FILE__, '/'));
echo
$script_directory . '<br />';
echo
$included_directory . '<br />';
?>
If you have a script that only includes the script written above in a directory called 'includer', and I access it from a web browser, this will be what I see:

/path/to/includer/
/path/to/included/
From Under A Rock...
31-Jul-2007 11:49
This small snippet will build the current script's url.  No muss, no fuss:

<?php

$self_url
= sprintf('http%s://%s%s',
  (isset(
$_SERVER['HTTPS']) && $_SERVER['HTTPS'] == TRUE ? 's': ''),
 
$_SERVER['HTTP_HOST'],
 
$_SERVER['REQUEST_URI']
);

?>
opez.org
30-Jul-2007 06:14
I couldn't find a better way... Here is a simple line of code that will give you the path to the current file/script:

<?php

$path_only
= implode("/", (explode('/', $_SERVER["SCRIPT_FILENAME"], -1)));

print
$path_only; // /home/worldpeace/public_html/test

print $_SERVER["SCRIPT_FILENAME"]; // /home/worldpeace/public_html/test/test.php

?>

I use this to build INCLUDE commands that call a file determined by a variable [ path + / + file ]. Dont forget the /

I hope this inspires someone.
mathiasrav at gmail dot com
28-Jul-2007 11:31
Based on dlyaza's snippet posted at 22-Oct-2006 12:33, here's getip() which gets the IP, first checking some known custom proxy headers for validity and then falling back to REMOTE_ADDR if none are found/match.

<?php
function getip() {
  static
$ip = false;
  if (
$ip !== false) return $ip;
  foreach (array(
'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $aah) {
    if (!isset(
$_SERVER[$aah])) continue;
   
$curip = $_SERVER[$aah];
   
$curip = explode('.', $curip);
    if (
count($curip) !== 4) break; // If they've sent at least one invalid IP, break out
   
foreach ($curip as &$sup) if (($sup = intval($sup)) < 0 or $sup > 255) break 2;
   
$curip_bin = $curip[0] << 24 | $curip[1] << 16 | $curip[2] << 8 | $curip[3];
    foreach (array(
     
//    hexadecimal ip  ip mask
     
array(0x7F000001,     0xFFFF0000), // 127.0.*.*
     
array(0x0A000000,     0xFFFF0000), // 10.0.*.*
     
array(0xC0A80000,     0xFFFF0000), // 192.168.*.*
   
) as $ipmask) {
      if ((
$curip_bin & $ipmask[1]) === ($ipmask[0] & $ipmask[1])) break 2;
    }
    return
$ip = $curip;
  }
  return
$ip = $_SERVER['REMOTE_ADDR'];
}
?>
jmv a jmvware d com
25-Jul-2007 10:32
The preceding note by krausbn works well, but be aware that whatever you use to parse it needs to urldecode the data
krausbn at php dot net
12-Jul-2007 02:35
On very low level POSTs (AJAX, XML RPC etc.) the $GLOBALS['HTTP_RAW_POST_DATA'] var might not contain data because of your php.ini settings. If that's the case you can use php://input to retrieve this low level data:

    // read raw POST data
$input = file_get_contents('php://input');
seb at omegasoft dot co dot uk
11-Jul-2007 05:19
More attractive way for displaying a URL

<?php

function get_url($show_port = false)
{
    if(
$_SERVER['HTTPS'])
    {
       
$my_url = 'https://';
    }
    else
    {
       
$my_url = 'http://';
    }

   
$my_url .= $_SERVER['HTTP_HOST'];

    if(
$show_port)
    {
       
$my_url .= ':' . $_SERVER['SERVER_PORT'];
    }

   
$my_url .= $_SERVER['SCRIPT_NAME'];

    if(
$_SERVER['QUERY_STRING'] != null)
    {   
       
$my_url .= '?' . $_SERVER['QUERY_STRING'];
    }

    return
$my_url;
}

echo
get_url(); // Outputs: http://localhost/
echo get_url(true); // Outputs: http://localhost:80/

?>
djaped at yahoo dot com
20-Jun-2007 05:49
Current Page URL
<?php
$urlh
= getenv(HTTP_HOST);
$url = "http://$urlh";
echo
' '.$url.$_SERVER['SCRIPT_NAME'];
?>
pecili
mike
12-Jun-2007 11:19
<?php
   
/*
    Simple function to get current page URL using comman PHP variables
   
    Function inputs:
        $base if set to true will add the basename to the URL
        $www if set to true will add www. to host if not found
        $query if set to true will add the query string to the URL
        $echo if set to true will echo the URL instead of just returning it
    */
   
function get_url($base = true, $www = true, $query = true, $echo = false){
       
$URL = ''; //open return variable
       
$URL .= (($_SERVER['HTTPS'] != '') ? "https://" : "http://"); //get protocol
       
$URL .= (($www == true && !preg_match("/^www\./", $_SERVER['HTTP_HOST'])) ? 'www.'.$_SERVER['HTTP_HOST'] : $_SERVER['HTTP_HOST']); //get host
       
$path = (($_SERVER['REQUEST_URI'] != '') ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF']); //tell the function what path variable to use
       
$URL .= ((pathinfo($path, PATHINFO_DIRNAME) != '/') ? pathinfo($path, PATHINFO_DIRNAME).'/' : pathinfo($path, PATHINFO_DIRNAME)); //set up directory
       
$URL .= (($base == true) ? pathinfo($path, PATHINFO_BASENAME) : ""); //add basename
       
$URL  = preg_replace("/\?".preg_quote($_SERVER['QUERY_STRING'])."/", "", $URL); //remove query string if found in url
       
$URL .= (($query == true && $_SERVER['QUERY_STRING'] != '') ? "?".$_SERVER['QUERY_STRING'] : ""); //add query string
       
if($echo == true){
            echo
$URL;
        }else{
            return
$URL;
        }
    }
   
   
/* Example */
   
$page_url = get_url();
    echo
$page_url;
?>
Mike
22-May-2007 12:27
Using HTTP_REFERER and parse_url() to display the host of the URL that a vistor came to your site from.

<?php
   
if($_SERVER['HTTP_REFERER'] != ''){
       
$URL = parse_url($_SERVER['HTTP_REFERER']);
        echo
"Welcome, <b>".$URL['host']."</b> visitor!";
    }
?>
deceze at gmail dot YesThatsGoogleMail dot com
11-Apr-2007 05:37
If you're working with $_GET a lot and need to preserve already set variables in a link for the next page, this function is pretty handy for simplifying the process of generating a new URL:

string setUrlVariables([string var, string value], [varN, valueN], ...)

<?php

function setUrlVariables() {
 
$arg = array();
 
$string = "?";
 
$vars = $_GET;
  for (
$i = 0; $i < func_num_args(); $i++)
   
$arg[func_get_arg($i)] = func_get_arg(++$i);
  foreach (
array_keys($arg) as $key)
   
$vars[$key] = $arg[$key];
  foreach (
array_keys($vars) as $key)
    if (
$vars[$key] != "") $string.= $key . "=" . $vars[$key] . "&";
  if (
SID != "" && SID != "SID" && $_GET["PHPSESSID"] == "")
   
$string.= htmlspecialchars(SID) . "&";

  return
htmlspecialchars(substr($string, 0, -1));
}

?>

You use it like this:

<a href="nextpage.php<?php echo setUrlVariables(); ?>">Link</a>

In this case setUrlVariables() will simply add all the $_GET variables of the current page/URL and even takes care of the PHPSESSID if you use one (and didn't change the default variable name). The above HREF would complete to e.g.:

"nextpage.php?var=21&amp;PHPSESSID=BI89J"

If you supply arguments, do it like this:

<?php echo setUrlVariables("user", "foobar"); ?>

This would complete the HREF to e.g.:

"nextpage.php?user=foobar&amp;var=21&amp;PHPSESSID=BI89J"

Unsetting variables works by supplying an empty value:

<?php echo setUrlVariables("var", ""); ?>

"nextpage.php?user=foobar&amp;PHPSESSID=BI89J"

setUrlVariables() also makes sure it produces "pretty URLs", so it doesn't output any unnecessary garbage. ;)

<?php
  session_destroy
();
  echo
setUrlVariables("user", "");
?>

"nextpage.php"
danvasile at pentest dot ro
21-Mar-2007 10:22
If you have problems with $_SERVER['HTTPS'], especially if it returns no values at all you should check the results of phpinfo(). It might not be listed at all.
Here is a solution to check and change, if necessary, to ssl/https that will work in all cases:

<?php
if ($_SERVER['SERVER_PORT']!=443) {
$sslport=443; //whatever your ssl port is
$url = "https://". $_SERVER['SERVER_NAME'] . ":" . $sslport . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>

Of course, this should be done before any html tag or php echo/print.
bosmeew at gmail dot com
18-Feb-2007 04:43
To get the server address, you can use $_SERVER['SERVER_ADDR']. However, this only works when your PHP process is running on a webserver, not when running PHP as CLI. Here is a function which will also return the server address when running on linux (eth0 is hardcoded as the network interface, modify if necessary).

<?php

function getServerAddress() {
    if(
$_SERVER['SERVER_ADDR']) {
        return
$_SERVER['SERVER_ADDR'];
    }
   
   
$ifconfig = shell_exec('/sbin/ifconfig eth0');
   
preg_match('/addr:([\d\.]+)/',$ifconfig,$match);
   
    return
$match[1];
}

?>
borg at sven-of-nine dot de
30-Jan-2007 01:22
Simple function to determine if a visitor is an agent or not

function isbot($agent="")
    {
    //Handfull of Robots
    $bot_array      =array("jeevesteoma",
                                   "msnbot",
                                   "slurp",
                                   "jeevestemoa",
                                   "gulper",
                                   "googlebot",
                                   "linkwalker",
                                   "validator",
                                   "webaltbot",
                                   "wget");
    //no agent given => read from globals
    if ($agent=="")
        {
        @$agent=$_SERVER["HTTP_USER_AGENT"];
        }
    //replace all but alpha
    $agent=strtolower(preg_replace("/[^a-zA-Z _]*/","",$agent));
    //check für intersections
    return((BOOL)count(array_intersect(explode(" ",$agent),$bot_array)));
    }
Joe Marty
24-Jan-2007 09:53
I think it is very important to note that PHP will automatically replace dots ('.') AND spaces (' ') with underscores ('_') in any incoming POST or GET (or REQUEST) variables.

This page notes the dot replacement, but not the space replacement:
http://us2.php.net/manual/en/language.variables.external.php

The reason is that '.' and ' ' are not valid characters to use in a variable name.  This is confusing to many people, because most people use the format $_POST['name'] to access these values.  In this case, the name is not used as a variable name but as an array index, in which those characters are valid.

However, if the register_globals directive is set, these names must be used as variable names.  As of now, PHP converts the names for these variables before inserting them into the external variable arrays, unfortunately - rather than leaving them as they are for the arrays and changing the names only for the variables set by register_globals.

If you want to use:
<input name="title for page3.php" type="text">

The value you will get in your POST array, for isntance would be:
$_POST['title_for_page3_php']
NeoSmart Technologies
18-Nov-2006 04:22
The *only* way to make Request_URI work as a 100% Apache-Compliant server variable on IIS/Windows is to use an Isapi Filter - as documented at http://neosmart.net/blog/archives/291 . The various steps mentioned below *completely* fail when a rewrite engine is employed, since IIS will *never* return a non-existent path (i.e. the actual pretty-URI used) via its server variables.

This also applies to accessing index.php via a folder.
For instance, calls made to /folder/ will appear as /folder/index.php and not /folder/.

The fix is to use the ISAPI filter provided at http://neosmart.net/blog/archives/291

You don't have to modify any of the actual scripts once this filter is in place - it automatically intercepts calls to REQUEST_URI and replaces them with the actual user-entered path.
me at tommygeorge dot com
09-Nov-2006 06:59
I'm sure this is elsewhere, but since 'chris dot chaudruc at gmail dot com' posted his example, I thought I would share a quick function I use to force HTTPS protocol on a page, without having to know the scripts name...

<?php
function ForceHTTPS()
{
    if(
$_SERVER['HTTPS'] != "on"
    {
      
$new_url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
      
header("Location: $new_url");
       exit;
    }
}
?>

Correct me if part of this doesn't work right. I've always used *nix based servers for PHP, so I might not be aware of certain windows limitations. Thanks.
Uili - e-info(at)tunenami.com
25-Oct-2006 12:34
Andy Staudacher may have addressed this in his bug fix but just for clarifacation when reading a cookie $_COOKIE reads only the most accurate domain including sub domain. If you have cookies for .bar.com and foo.bar.com and the user is at foo.bar.com $_COOKIE only returns the cookie data from foo.bar.com but if the user is at www.bar.com the data from .bar.com will be read if there is no cookie for www.bar.com.
dlyaza aT yahoo DOT com
22-Oct-2006 09:33
Get Real IP Address; If some one Know More than below, let us to see

if (getenv('HTTP_CLIENT_IP')) {
$IP = getenv('HTTP_CLIENT_IP');
}
elseif (getenv('HTTP_X_FORWARDED_FOR')) {
$IP = getenv('HTTP_X_FORWARDED_FOR');
}
elseif (getenv('HTTP_X_FORWARDED')) {
$IP = getenv('HTTP_X_FORWARDED');
}
elseif (getenv('HTTP_FORWARDED_FOR')) {
$IP = getenv('HTTP_FORWARDED_FOR');
}
elseif (getenv('HTTP_FORWARDED')) {
$IP = getenv('HTTP_FORWARDED');
}
else {
$IP = $_SERVER['REMOTE_ADDR'];
}
seanhickey at gmail dot com
20-Sep-2006 12:46
Note that class objects will not be in the $GLOBALS array until *after* the classe's constructor returns.

<?php
class A
{
    public function
__construct()
    {
       
var_dump($GLOBALS);
    }
}

$a = new A;
var_dump($GLOBALS);
?>

The first var_dump() inside the __construct() method will not contain the value of $a, while the second one will.
Alexander Hars
19-Sep-2006 12:16
If you want to use a form with multiple checkboxes (e.g. one per row) and assign the same name to each checkbox then the name needs to end with []. This tells PHP to put all checked values into an array variable.
For example:
<input type="checkbox" name="id[]" value="value_1">
<input type="checkbox" name="id[]" value="value_2">
..
<input type="checkbox" name="id[]" value="value_x">

You can now retrieve all values by using:
   $values = $_POST['id'];

If the name does not end with [], then only a single value will be available via the $_POST variable even if the user checks several checkboxes.
trevor
08-Aug-2006 08:49
I needed to do the exact same thing as jwl007 (sort by clicking links) but I needed it to append the variable to the query string if it didn't already exist. Here's the function I'm using:

<?php
function setGetVar($var, $val){
   
$request_uri = $_SERVER["REQUEST_URI"];
    if(
strstr($request_uri, $var)) {
        return
preg_replace("/$var=[\\d\\w]*/", "$var=$val", $request_uri);
    } elseif(
strstr($request_uri, "?")) {
        return
$request_uri . "&" . $var . "=" . $val;
    } else {
        return
$request_uri . "?" . $var . "=" . $val;
    }
}
?>

<a href="<?php echo setGetVar("orderby", "lname"); ?>">Sort by Last Name</a>
<a href="<?php echo setGetVar("orderby", "fname"); ?>">Sort by First Name</a>
jmurphy at hsdirect dot co dot uk
26-Jul-2006 05:17
As above the $_SERVER['request_uri']

is replaced in windows iis with

$_SERVER['script_name']
jameslporter at gmail dot com
05-May-2006 10:19
Refer to CanonicalName if you are not getting the ServerName in the $_SERVER[SERVER_NAME] variable....This was a pain to figure out for me...now it works as expected by turning canonical naming on.

http://www.apacheref.com/ref/http_core/UseCanonicalName.html
tchamp
26-Apr-2006 05:24
Be careful with HTTP_HOST behind a proxy server.   Use these instead.
[HTTP_X_FORWARDED_FOR]
[HTTP_X_FORWARDED_HOST]
[HTTP_X_FORWARDED_SERVER]

In my situation, I used [HTTP_X_FORWARDED_SERVER] in place of [HTTP_HOST] in order get the machine and hostname (www.myurl.com)
Ben XO
14-Apr-2006 04:18
So you have an application in your web space, with a URL such as this:

http://<host>/<installation_path>/

and pages such as

http://<host>/<installation_path>/subfolder1/subfolder2/page.php

You have a file called config.php in <installation_path> which is include()d by all pages (in subfolders or not).

How to work out <installation_path> without hard-coding it into a config file?

<?php

// this is config.php, and it is in <installation_path>
// it is included by <installation_path>/page.php
// it is included by <installation_path>/subfolder/page2.php
// etc

$_REAL_SCRIPT_DIR = realpath(dirname($_SERVER['SCRIPT_FILENAME'])); // filesystem path of this page's directory (page.php)
$_REAL_BASE_DIR = realpath(dirname(__FILE__)); // filesystem path of this file's directory (config.php)
$_MY_PATH_PART = substr( $_REAL_SCRIPT_DIR, strlen($_REAL_BASE_DIR)); // just the subfolder part between <installation_path> and the page

$INSTALLATION_PATH = $_MY_PATH_PART
   
? substr( dirname($_SERVER['SCRIPT_NAME']), 0, -strlen($_MY_PATH_PART) )
    :
dirname($_SERVER['SCRIPT_NAME'])
;
// we subtract the subfolder part from the end of <installation_path>, leaving us with just <installation_path> :)

?>
todd dot kisov at yahoo dot com
03-Apr-2006 12:11
To convert query string parameter values ($_GET, $_REQUEST), which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string (%uNNNN%uNNNN%uNNNN) fast and simple is to use PECL JSON extension:

function JavaScript_Unicode_URL_2_Str($js_uni_str) {
        $res = preg_replace('/%u([[:alnum:]]{4})/', '\\u\1', $js_uni_str);
        $res = str_replace('"', '\"', $res); // if in str "
        $res = json_decode('["'.$res.'"]'); // JavaScrip array with string element
        $res = $res[0];
        $res = iconv('UTF-8', ini_get('default_charset'), $res);
        return $res;
    }
01-Apr-2006 08:56
I was unable to convince my hosting company to change their installation of PHP and therefore had to find my own way to computer $_SERVER["DOCUMENT_ROOT"].  I eventually settled on the following, which is a combination of earlier notes (with some typos corrected):

<?php
if ( ! isset($_SERVER['DOCUMENT_ROOT'] ) )
 
$_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(
   
$_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF']) ) );
?>
mjs at beebo dot org
30-Mar-2006 11:24
Note that PHP_SELF will not be equal to REQUEST_URI under Apache if mod_rewrite has been used to move one URL to another--PHP_SELF will contain the rewritten address, and REQUEST_URI will contain the URL the user sees in their browser.
adam3000 at gmail dot com
15-Mar-2006 08:30
I was trying to find an alternative to $_SERVER['REQUEST_URI'] for a Windows NT set up and the ones below didn't really work for me so here's my solution using eustf at hotmail dot com's suggestion of $_SERVER['PHP_SELF']:

// if 'REQUEST_URI' isn't available then ...
if(!isset($_SERVER['REQUEST_URI'])) {
   
    // ... set my own request url and ...
    $temp_request_url = $_SERVER['PHP_SELF'];
   
    // ... test for and add url variables to my request url ...
    if (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
        $temp_request_url .= (strpos($updateGoTo, '?')) ? "&" : "?";
        $temp_request_url .= $HTTP_SERVER_VARS['QUERY_STRING'];
        }

} else {
    // ... otherwise use the regular 'REQUEST_URI'
    $temp_request_url = $_SERVER['REQUEST_URI'];
}
Aardvark
07-Mar-2006 11:35
$_GET may not handle query string parameter values which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string.
To handle this the query parameter value can be obtained  using a function such as:

function getQueryParameter ($strParam) {
  $aParamList = explode('&', $_SERVER['QUERY_STRING']);
  $i = 0;
  while ($i < count($aParamList)) {
    $aParam = split('=', $aParamList[$i]);
    if ($strParam == $aParam[0]) {
      return $aParam[1];
    }
  }
  return "";
}

or by directly building an array or query string values and then processing the parameter string using a function such as the "unescape" function which can be found at http://www.kanolife.com/escape/2006/03/unicode-url-escapes-in-php.html (or http://www.kanolife.com/escape/ for related info).
justin dot (nospam)george at gmail dot com
28-Feb-2006 10:00
Note that it's a very, very bad idea to append to global variables in a loop, unless you really, really mean to do so in a global context. I just a while ago hung my server with a snippet of code like this:

<?php
$host 
= $_SERVER['HTTP_HOST'];
$uri  = rtrim($_SERVER['PHP_SELF'], "/\\");

  
$GLOBALS['SITE_ROOT'] = "http://$host$uri";

while (
$i < somenumber)
readfile($GLOBALS['SITE_ROOT'] = $GLOBALS['SITE_ROOT'] . '/this/file.php');
$i++
}
?>

While it is an entertaining and unusual method of creating very long URLs and breaking servers, it's a pretty awesomely bad idea

(Especially considering that the script in question ran concurrently with others of it's type, so the value in $GLOBALS['SITE_ROOT'] was unknown.)
nathan
22-Feb-2006 06:05
Also on using IPs to look up country & city, note that what you get might not be entirely accurate.  If their ISP is based in a different city or province/state, the IPs may be owned by the head office, and used across several areas. 
You also have rarer situations where they might be SSHed into another server, on the road, at work, at a friend's...  It's a nice idea, but as the example code shows, it should only be used to set defaults.
geza at turigeza dot com
11-Feb-2006 03:13
Above the manual says

'$_REQUEST is an associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.'
However
$_REQUEST doesn't always contain the same elements as

$_GET+$_POST+$_REQUEST;

Basically if you add an element to the $_POST array that element does not automatically get added to REQUEST as well. It's easy to understand why :)

<?php
$_POST
['geza'] = 'geza';
$_GET['bela'] = 'bela';

echo
'<pre>';
print_r($_POST);
print_r($_GET);
print_r($_REQUEST);
echo
'</pre>';
?>

will output this
Array
(
    [geza] => geza
)
Array
(
    [bela] => bela
)
Array
(
)
marsh at NOSPAM-TAKETHATSPAMMER dot uri
20-Jan-2006 06:05
The solution advanced by info at meshkaat dot com does not work correctly on machines with IIS configured to use
a virtual directory as the launch point. The address strings for $_SERVER['SCRIPT_FILENAME'] and $_SERVER['PHP_SELF'] will not necessarily have the same name for the highest level directory in $_SERVER['PHP_SELF'], and therefore this solution will not return the proper value.
marsh at NOSPAM-TAKETHATSPAMMER dot uri dot edu
12-Jan-2006 05:57
Under Windows XP SP2 and IIS, $_SERVER('x') returns a path using forward slash '/' as the separator, where x is:

      PHP_SELF, SCRIPT_NAME

These arguments, however, all return a path using backward slash, '\' as the separator:

  __FILE__, SCRIPT_FILENAME, and DOCUMENT_ROOT (if you use one of the methods mentioned previously).

Also note that if the name of the last directory in the document root includes a space, the methods described above for setting DOCUMENT_ROOT will return a value that drops the everything past the space.
Andy Staudacher, gmx.ch add ast before @
20-Dec-2005 03:02
The following code is licensed under the GPL and it is from the gallery.menalto.com project.
<?php
   
/**
     * Fix the superglobal $_COOKIE to conform with RFC 2965
     *
     * We don't use $_COOKIE[$cookiename], because it doesn't conform to RFC 2965 (the
     * cookie standard), i.e. in $_COOKIE, we don't get the cookie with the most specific path for
     * a given cookie name, we get the cookie with the least specific cookie path.
     * This function does it exactly the other way around, to a) fix our cookie/login problems and
     * to b) conform with the RFC.
     * The PHP bug was already fixed in spring 2005, but we will have to deal with broken PHP
     * versions for a long time. See http://bugs.php.net/bug.php?id=32802.
     *
     * Fixes also another PHP cookie bug. PHP doesn't expect the cookie header to have
     * quoted-strings, but they are perfectly legal according to RFC 2965.
     *
     * The third bug fixed here is an MS Internet Explorer (IE) bug. When using default cookie
     * domains (no leading dot, don't set the domain in set-cookie), IE is supposed to return only
     * cookies that have the exact request-host as their domain.
     * Example: Cookies stored in the browser with cookie domains: .example.com, .www.example.com,
     *          example.com, www.example.com
     *          The request-host is www.example.com. Thus, IE should return all those cookies but
     *          the example.com cookie, because it's a default domain cookie and it doesn't match
     *          exactly the request-host. But IE returns the example.com cookie too.
     * As MS decided that it returns the cookie with the best domain-match first (unspecified in
     * RFC 2965), this wouldn't be a problem if PHP didn't select the last cookie in the
     * HTTP_COOKIE header. But with fixCookieVars(), this case is also fixed.
     *
     * This function reevaluates the HTTP Cookie header and populates $_COOKIE with the correct
     * cookies. We fix only non-array and non '[', ']' containing cookies for simplicity. To fix
     * our login problem, we'd have to fix only the GALLERYSID cookie anyway.
     *
     * @param boolean force the reevaluation of the HTTP header string Cookie
     * @param boolean unset static variable for testability
     */
   
function fixCookieVars($force=false, $unset=false)
?>
The source code can be found at:
http://cvs.sourceforge.net/viewcvs.py/gallery/gallery2/
modules/core/classes/GalleryUtilities.class?rev=1.146&view=markup
info at meshkaat dot com
06-Dec-2005 03:03
How to get $_SERVER["DOCUMENT_ROOT"] on IIS :

if(!isset($_SERVER["DOCUMENT_ROOT"]))
{$_SERVER["DOCUMENT_ROOT"]=substr($_SERVER['SCRIPT_FILENAME'] , 0 , -strlen($_SERVER['PHP_SELF'])+1 );
}

it simply works!
chris at vault5 dot com
30-Nov-2005 05:17
Since $_SERVER['DOCUMENT_ROOT'] is not always present, the following will provide it where $_SERVER dosen't.

<?php
function resolveDocumentRoot() {
   
$current_script = dirname($_SERVER['SCRIPT_NAME']);
   
$current_path   = dirname($_SERVER['SCRIPT_FILENAME']);
   
   
/* work out how many folders we are away from document_root
       by working out how many folders deep we are from the url.
       this isn't fool proof */
   
$adjust = explode("/", $current_script);
   
$adjust = count($adjust)-1;
   
   
/* move up the path with ../ */
   
$traverse = str_repeat("../", $adjust);
   
$adjusted_path = sprintf("%s/%s", $current_path, $traverse);

   
/* real path expands the ../'s to the correct folder names */
   
return realpath($adjusted_path);   
}

?>

It counts the number of folders down the path we are in the URL, then moves that number of folders up the current path... end result should be the document root :)

It wont work with virtual folders or in any situation where the folder in the URL dosen't map to a real folder on the disk (like when using rewrites).
lorenpr at gmail dot com
02-Nov-2005 01:04
Here's a simple function that has proven reliable for me in checking if a user has refreshed the current page on a website.

function pageRefreshed()
{
  if($_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
     return true;

   return false;
}
webmaster at eclipse dot org
11-Oct-2005 05:01
In response to tobias at net-clipping dot de

It is not an Apache bug.  Please read http://httpd.apache.org/docs/2.1/mod/core.html#errordocument carefully (2.1 version here, 2.0 and 1.x is similar). 

In short, if your ErrorDocument start with http:// Apache sends a redirect (302) to the error document, hence losing your original referer. If your ErrorDocument points to a relative path, 404 is maintained and so are your variables.

From the Apache manual:

"Note that when you specify an ErrorDocument  that points to a remote URL (ie. anything with a method such as http in front of it), Apache will send a redirect to the client to tell it where to find the document, even if the document ends up being on the same server. This has several implications, the most important being that the client will not receive the original error status code, but instead will receive a redirect status code. This in turn can confuse web robots and other clients which try to determine if a URL is valid using the status code. In addition, if you use a remote URL in an ErrorDocument 401, the client will not know to prompt the user for a password since it will not receive the 401 status code. Therefore, if you use an ErrorDocument 401 directive then it must refer to a local document."

D.
drew dot griffiths at clare dot net
30-Sep-2005 06:51
Re: You can take advantage of 404 error to an usable redirection using REQUEST_URI ...

Whilst this is effective, a line in the .htaccess such as:

RewriteEngine On
RewriteRule ^profiles/([A-Za-z0-9-]+) showprofile.php?profile=$1 [L,NC,QSA]

will throw the requested profile in a variable $profile to the showprofile.php page. 

You can further enhance the url (e.g http://servername/profiles/Jerry/homeaddress/index.htm) and the second variable value homeaddress becomes available in $url_array[3] when used below $url_array=explode("/",$_SERVER['REQUEST_URI']);  

Hope this helps - Works well for me

Drew
jeromenelson at gmail dot com
19-Sep-2005 01:56
You can take advantage of 404 error to an usable redirection using REQUEST_URI ...

For example the following program can retrieve the information for the 'search_string', for a given URI:  http://servername/profiles/search_string, even though there's no such path.
Do the following steps..

Step 1: Edit Apache config:  set
        ErrorDocument 404 "/missing.php" 
Step 2: Write the missing.php as follows ...

<?
$mainPath
= "/profiles/";                                       // Example: http://servername/profiles/search_string
$mpLength = strlen( $mainPath  );                               
$request_uri = $_SERVER['REQUEST_URI'];

if (
$mainPath != substr($request_uri,0,$mpLength) ) {          // Check if the given URI is valid
   
echo "404 Page Not Found !";
    exit();
}

$name = substr ($request_uri , $mpLength ) ;                    // Extract the string to be searched

echo "You have searched for the profile of Mr. $name";

/** Here you can write the code to retrieve and display
     the $name's  information from the database
*/
?>

Step 3: Now try http://servername/profiles/Jerry
    (of course, there shouldn't be a file/folder in the server like "DOCROOT/profiles/Jerry" )

     output: You have searched for the profile of Mr. Jerry

God Bless You!
Angelina Bell
04-Aug-2005 06:55
Warning:
$_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME'] may not always be set correctly.
Some web hosts implement php as a CGI in such a way that they can turn it on or off for each virtual domain.  Several $_SERVER and $_ENV variable values may be incorrect for documents in subdirectory subdomains of these virtual domains.

An include-file function or constant, instead of PHP_SELF or some other predefined variable throughout a website, will make it easier to "fix" an entire website in case something changes.
<?php
function true_url_path() {
// Pick the predefined variable that works on your server
     
return $_ENV['SCRIPT_URL'];
}
?>
Or
<?php
// Pick the predefined variable that works on your server
define("TRUE_URL_PATH", $_ENV['SCRIPT_URL']);
?>
Gregory Boshoff
31-Jul-2005 12:41
$_SERVER['QUERY_STRING']

Does not contain XHTML 1.1 compliant ampersands i.e. &amp;

So you will need to do something like this if you are to use $_SERVER['QUERY_STRING'] in URL's.

//  XHTML 1.1 compliant ampersands
$_SERVER['QUERY_STRING'] =
str_replace(array('&amp;', '&'), array('&', '&amp;'),
$_SERVER['QUERY_STRING']);
New York PHP
24-Jul-2005 04:59
Warning: $_SERVER['PHP_SELF'] can include arbitrary user input. The documentation should be updated to reflect this.

The request "http://example.com/info.php/attack%20here" will run /info.php, but in Apache $_SERVER['PHP_SELF'] will equal "/info.php/attack here". This is a feature, but it means that PHP_SELF must be treated as user input.

The attack string could contain urlencoded HTML and JavaScript (cross-site scripting) or it could contain urlencoded linebreaks (HTTP response-splitting).

The use of $_SERVER['SCRIPT_NAME'] is recommended instead.
eustf at hotmail dot com
21-Jul-2005 06:05
REQUEST_URI not defined on Windows XP and IIS 5.1
I have seen different script on the web and in this list but they don't work fully. This one seems to work:

if(!isset($_SERVER['REQUEST_URI'])) {
  $arr = explode("/", $_SERVER['PHP_SELF']);
  $_SERVER['REQUEST_URI'] = "/" . $arr[count($arr)-1];
  if ($_SERVER['argv'][0]!="")
    $_SERVER['REQUEST_URI'] .= "?" . $_SERVER['argv'][0];
}
daniel at softel dot jp
16-Jul-2005 09:43
Note that $php_errormsg may contain a newline character. This can be problematic if you are trying to output it with a JavaScript "alert()" for example.
andy dot gajetzki at gmail dot com
06-Jul-2005 04:22
I wanted to be able to embed a variable in the path. This is useful when, for example, images are rendered on the fly and you would like them to have different urls.

Here is an illustration:

www.somesite.com/image.php/IMAGETEXTHERE

This would return an image with the text after "image.php/" contained in it.

I could not recall the name of this feature, so I made a work-around in PHP...

<?       
       
function getPathVariables() {
       
$sPathPS = $_SERVER[PHP_SELF];
       
$sPathFS = __FILE__;

       
$aPathPS = array_reverse(explode("/", $sPathPS));
       
$aPathFS = array_reverse(explode("/", $sPathFS));

       
$aImageArgs = array();
       
$x = 0;

        while (
$aPathPS[$x] != $aPathFS[$x] && $aPathPS[$x] != $aPathFS[0] ) {
               
array_unshift($aImageArgs, $aPathPS[$x])        ;
               
$x++;
        }
        return
$aImageArgs;

}
?>

This function will return an array containing each "/" delimited portion of the path after the script name itself.
notes at arbee dot co dot uk
27-Jun-2005 05:14
Note that $_SERVER['QUERY_STRING'] behaves differently under IIS/Apache.

In Apache (at least on Windows) it is ALWAYS set - if no query string was specified in the URL, $_SERVER['QUERY_STRING'] is initialised as an empty string.

In IIS, if no query string is included in the URL, $_SERVER['QUERY_STRING'] is NOT SET, so trying to access it without checking for its existence will generate notices.
koerner-familie at t-online dot de
21-Jun-2005 04:52
If you want to make a copy of $BLOBALS (e.g. to test whether which tariables were changed during script-runtime,
<?php $___debug_var_dump = $GLOBALS; ?>
will _NOT_ make a copy in PHP4 (tested with 4.3.11). Use
<?php $___debug_var_dump = array_merge($GLOBALS, array()); ?> instead, but ONLY for testing purpose.
Best regards, Peter
purplebz at hotmail dot com
19-Jun-2005 11:35
How to get $_SERVER['REQUEST_URI'] on IIS (WinXP):

if ( empty($_SERVER['REQUEST_URI']) ) {
   $arr = explode("/", $_SERVER['PHP_SELF']);
   $_SERVER['REQUEST_URI'] = $arr[count($arr)-1];
}
xangelusx at hotmail dot com
13-Jun-2005 11:03
A note about the QUERY_STRING variable when using IIS:

I have found that IIS does not handle large query strings gracefully when passed from PHP. In addition to truncating them to around 1024 kb, I have seen IIS actually add data from other server variables to the end of the truncated data.

This occurred on Windows 2000 server running IIS 5.0 and PHP 4.3.8.  The problem did not occur when handled by Apache, even on another Windows server.

Note: I realize passing this much data is best accomplished using the POST method, which would avoid this problem all together. I'm merely detailing a problem that I came across.

I have created a page that includes the (very long) query string that was used and some of the results that I saw while testing. It can be viewed at http://www.csb7.com/test/php_iis_qs_limit/. I didn't want to include it here as it would stretch the page out significantly.

~Chris Bloom
mfyahya at gmail dot com
07-Jun-2005 04:33
If you use Apache's redirection features for custom error pages or whatever, the following Apache's REDIRECT variables are also available in $_SERVER:
$_SERVER['REDIRECT_UNIQUE_ID]'
$_SERVER['REDIRECT_SCRIPT_URL]'
$_SERVER['REDIRECT_SCRIPT_URI]'
$_SERVER['REDIRECT_SITE_ROOT]'
$_SERVER['REDIRECT_SITE_HTMLROOT]'
$_SERVER['REDIRECT_SITE_CGIROOT]'
$_SERVER['REDIRECT_STATUS]'
$_SERVER['REDIRECT_QUERY_STRING]'
$_SERVER['REDIRECT_URL]'

I'm not sure if this is a complete list though
mp at wds-tech dot de
02-Jun-2005 10:12
Also aviable is the $_SERVER['SERVER_ADDR'] which returns the current IP of the server the script is running on.
webKami (et) AKDomains.com
24-May-2005 09:47
PHP Secure Class to prevent XSS Attacks

Although this is not bullet proof but it would give you an idea on how to filter incoming data.

Copyleft : LGPL
Idea by: phpsec GROUP @ PHP|arch

Coded By: webKami

For those who are new to PHP and just heard of XSS attacks, this is the basic rule.

"NEVER EVER TRUST EXTERNAL DATA"

For this purpose I have coded a class that can be used to filter all external data, from POST, GET, COOKIE and even your own arrays.

An example is that if you need only integers from a certain parameter just request for integer
e.g. getVarInt("id")

You can even tell it to give you a default value if param is not set, so that your page would not FAIL in case of a NULL value
e.g. getVarInt("id",1)

You can also fetch data from a param array, like a set of colors
e.g. getVarInt("colors",0,0)
e.g. getVarInt("colors",0,1)

Get these variables in a loop limited by the count of that array's elements
e.g. getVarCount("colors")

The complete code of class and its usage can be found here

http://www.webkami.com/programming/php/php-secure-class-to-avoid-xss

I am posting the usage below.

<?

//for url variables
$req = new requestGet();
echo
"Int:".$req->getVarInt("id")."<br />";
echo
"Alpha:".$req->getVarAlpha("name",4)."<br />";

//for form variables
$req = new requestPost();
echo
"Int:".$req->getVarInt("id")."<br />";
echo
"Alpha:".$req->getVarAlpha("name",4)."<br />";

//for cookies
$req = new requestCookie();
echo
"Int:".$req->getVarInt("id")."<br />";
echo
"Alpha:".$req->getVarAlpha("name",4)."<br />";

//for your own variables, set your values to an item in an array and you can modify the array

$filter["id"]=4;
$filter["name"]="Ali";
$req = new requestFilter($filter);
echo
"Int:".$req->getVarInt("id")."<br />";
echo
"Alpha:".$req->getVarAlpha("name",4)."<br />";

?>
JM
17-May-2005 11:08
The $_SERVER['PHP_AUTH_*'] variables are not available in safe mode.  See http://www.php.net/features.http-auth
www dot php dot net at webdevelopers dot cz
12-May-2005 04:01
Simple function that selects "best" language for the user from the list of available languages:

function chooseLang($availableLangs) {
    $pref=array();
    foreach(split(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]) as $lang) {
        if (preg_match('/^([a-z]+).*?(?:;q=([0-9.]+))?/i', $lang.';q=1.0', $split)) {
            $pref[sprintf("%f%d", $split[2], rand(0,9999))]=strtolower($split[1]);       
        }
    }
    krsort($pref);
    return array_shift(array_merge(array_intersect($pref, $availableLangs), $availableLangs));
}
 
echo 'BESTLANG: '.chooseLang(array('cs', 'sk', 'ru', 'en'));

Daniel "elixon" Sevcik
exaton at free dot fr
06-May-2005 09:23
With the arrival of the Google Web Accelerator, the problem of keeping track of users through $_SERVER['REMOTE_ADDR'] (for a much shorter while than with cookies) has reared its ugly head anew.

For those confronted with this issue, remember that Google implements the $_SERVER['HTTP_X_FORWARDED_FOR'] header giving the IP address of the connection that it proxies.

Hope this helps...
inbox at tanasity dot com
13-Apr-2005 04:23
Under Windows 2000, running IIS and PHP 4.3.10, $_SERVER['SCRIPT_NAME'] is not available, however $_SERVER['SCRIPT_FILENAME'] is present and seems to contain the same information.
javalizard at mac dot com
11-Apr-2005 02:02
My web host server will give my php the user preferred languages out over the order.  This means that I had to write a function for ordering the languages based upon their "q" value (rank from 1..0, 1 being the most preferred).  If you want an ordered list of user preferred languages use this function:

<?php
function orderedLanguages()
{
   
$languages = split(",", $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
   
$lang_q = Array();
    foreach(
$languages as $aLang ) {
       
$lang_array = split(";q=", trim( $aLang ) );
       
$lang = trim( $lang_array[0] );
        if( !isset(
$lang_array[1] ) )
           
$q = 1;
        else
           
$q = trim($lang_array[1]);
       
$lang_q["$lang"] = (float)$q;
    }
   
arsort($lang_q);
   
//extra code for making the languages key indexed
   
$i = 0;
   
$lang_index = Array();
    foreach(
$lang_q as $lang => $q) {
   
//    $lang_q[$i] = $lang; //add to the same array the index key/language
       
$lang_index[$i] = $lang; //add to a new array the index key/language
       
$i++;
    }
   
   
//return $lang_index; // uncomment for returning array with keys={0..n-1}, values={most..least preferred}
   
return $lang_q;
}

?>

While you can't reference the key by number, You can use foreach to pull elements.  This will be in order.   So getting the key with array_keys should work in the preferred order too.  I've added a few extra lines of commented code for reordering the array into one(s) that reference the language by number (if you need it)   :D
skrollster
26-Mar-2005 06:36
$_SERVER["REMOTE_USER"] and $_SERVER['PHP_AUTH_USER'] is the same variable i think..
anonymous
04-Mar-2005 12:12
I don't see the $_SERVER["REMOTE_USER"] listed in this document.
This displays the username used to login using .htaccess.
28-Feb-2005 04:41
Matt Johnson says that one should never urldecode() $_GET data. This is incorrect.

If magic_quotes_gpc is turned off in php.ini, then you *do* need to urldecode() $_GET data.

Having magic_quotes_gpc turned off is considered good practise.
17-Feb-2005 01:30
grlprgrmmr wrote:

you can use these to reconstructed the current page url.

<?php

echo 'http';
if(
$_SERVER['HTTPS']=='on'){echo 's';}
echo
'://'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
if(
$_SERVER['QUERY_STRING']>' '){echo '?'.$_SERVER['QUERY_STRING'];}

?>
______________

the $_SERVER['SERVER_PORT'] part should be changed to $_SERVER['HTTP_HOST']
Gregory Boshoff
14-Feb-2005 02:19
The Environment variable $ENV is useful for coding portable platform specific application constants.

// Define a Windows or else Linux root directory path
$_ENV['OS'] == 'Windows_NT' ? $path = 'L:\\www\\' : $path = ' /var/www/';

define('PATH', $path);

echo PATH;
magotes[at]netcabo.pt
12-Feb-2005 05:09
Sorry if this is old news to some, but it might not be obvious at a first glance:

If you are using $_SERVER['remote_addr'] as a way to keep track of a logged-in user (this can be useful to avoid several types of hacking), remember that it might not be the user's actual IP address!

I was trying to implement a login feature that used this, storing the IP into a DB. It went smoothly while on a LAN, but wrecked havoc when accepting outter connections.
grlprgrmmr uses gmail
10-Feb-2005 09:05
you can use these to reconstructed the current page url.

<?php

echo 'http';
if(
$_SERVER['HTTPS']=='on'){echo 's';}
echo
'://'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
if(
$_SERVER['QUERY_STRING']>' '){echo '?'.$_SERVER['QUERY_STRING'];}

?>

If $_SERVER['HTTPS']=='on' does not work for you,
try $_SERVER['SERVER_PORT']==443 (or whatever secure port is used)
JSP001
27-Jan-2005 12:15
Hi dotpointer,

I am new to php but I suggest a little modification of your script. Tell me what you think of it :

function getThisFile() {

[...]
    /* last resort __FILE__ */
    } else {
        $strScript = __FILE__;
    }
[...]
}

Thanks for this great function, I'll use it for my project !

Regards
niles AT atheos DOT net
26-Jan-2005 10:51
If your having problems returning $_SERVER variables using apache, be sure you enable:

ExtendedStatus On

in your httpd.conf file.

If it's off, then things like $_SERVER['HTTP_HOST'] won't be present.
marcus at lastcraft dot com
24-Jan-2005 02:02
The variable $php_errormsg is not populated if you have XDebug running.
arjini at gmail dot com
19-Jan-2005 02:29
Driven crazy by the lack of consistency with $_SERVER across installations? Check out this chart:

http://www.koivi.com/apache-iis-php-server-array.php
roy dot rico at gmail dot com
18-Jan-2005 11:48
if you are trying to use $php_errormsg, it acts more like a function than it does a variable.

example

   echo "<h1>";
   $php_errormsg;
   echo "</h1>";

will output:

   <h1>[the php error]<h1>

however, this command

   echo "<h1>" . $php_errormsg . "</h1>";

should produce the same thing, yet it produces

   [the php error]<h1></h1>

not sure if this is a "feature" or a "bug"
dotpointer
09-Jan-2005 11:26
Running Xitami in Windows 2000 and PHP 4.3.7, nor PHP_SELF or SCRIPT_FILENAME is not availiable. Trying SCRIPT_NAME instead. Here is a function that returns the filename of a script without slashes. Good for use in HTML FORM ACTION=""-arguments...

function getThisFile() {

 /* try to use PHP_SELF first... */
 if (!empty($_SERVER['PHP_SELF'])) {
  $strScript = $_SERVER['PHP_SELF'];
 /* otherwise, try SCRIPT_NAME */
 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
  $strScript = @$_SERVER['SCRIPT_NAME'];
 /* last resort - quit out and return nothing */
 } else {
  return null;
 }

 /* fint last frontslash in filename */
 $intLastSlash = strrpos($strScript, "/");

 /* check if last backslash is more far away in filename */
 if (strrpos($strScript, "\\")>$intLastSlash) {
  /* if so, use the backslash position instead */
  $intLastSlash = strrpos($strScript, "\\");
 }

 /* cut out from the last slash and to the end of the filename */
 return substr($strScript, $intLastSlash+1, strlen($strScript));
}

Tested on PHP 4.3.7/Win32 and PHP 5.0.3/Linux.
You may add more filepaths to the first if-section
to get more chances to catch up the filename if you can.
Matt Johnson
26-Dec-2004 02:50
A reminder: if you are considering using urldecode() on a $_GET variable, DON'T!

Evil PHP:

<?php
# BAD CODE! DO NOT USE!
$term = urldecode($_GET['sterm']);
?>

Good PHP:

<?php
$term
= $_GET['sterm'];
?>

The webserver will arrange for $_GET to have been urldecoded once already by the time it reaches you!

Using urldecode() on $_GET can lead to extreme badness, PARTICULARLY when you are assuming "magic quotes" on GET is protecting you against quoting.

Hint: script.php?sterm=%2527 [...]

PHP "receives" this as %27, which your urldecode() will convert to "'" (the singlequote). This may be CATASTROPHIC when injecting into SQL or some PHP functions relying on escaped quotes -- magic quotes rightly cannot detect this and will not protect you!

This "common error" is one of the underlying causes of the Santy.A worm which affects phpBB < 2.0.11.
mrnopersonality at yahoo dot com
19-Oct-2004 05:13
Nothing about the message-body ...

You can get cookies, session variables, headers, the request-uri , the request method, etc but not the message body. You may want it sometimes when your page is to be requested with the POST method.

Maybe they should have mentioned $HTTP_RAW_POST_DATA or php://stdin
hfuecks at phppatterns dot com
06-Sep-2004 10:21
Using Apache/mod_ssl, there are further environment variables available to check for an SSL connection (can be more useful than $_SERVER['SERVER_PORT']), documented here: http://www.modssl.org/docs/2.8/ssl_reference.html#ToC25

To test whether the client connected with SSL I can use $_SERVER['HTTPS'] e.g (with redirect to secured, current URL);

<?php
if ( !isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) != 'on' ) {
   
header ('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    exit();
}
?>
boaz at babylon dot com
30-Aug-2004 05:13
You can add $_SERVER["DOCUMENT_ROOT"] to IIS by editing the Environment Variables of your Windows server (was tested on WinXP SP2).

Right click on My Computer >> Properties >> Advanced.
In the System variables click on 'New' and Type in the name field 'DOCUMENT_ROOT' and in the value field  the path to your IIS document root folder.

Don't forget to restart your Windows (IIS restart won't load the new settings).
david at grant dot org dot uk
12-May-2004 03:34
$_SERVER['DOCUMENT_ROOT'] *is* supported by IIS, although only when running PHP as an ISAPI module.
youdontmeanmuch [at] yahoo.com
06-Apr-2004 06:20
Be carful when using $_SERVER['DOCUMENT_ROOT']; in your applications where you want to distribute them to other people with different server types. It isnt always supported by the webserver (IIS).
mortoray at ecircle-ag dot com
18-Dec-2003 07:32
The RAW / uninterpreted HTTP POst information can be accessed with:
    $GLOBALS['HTTP_RAW_POST_DATA']

This is useful in cases where the post Content-Type is not something PHP understands (such as text/xml).
josh,endquote,com
04-Dec-2003 01:54
Running PHP 4.3 under IIS 5 on Windows XP, there is no $_SERVER['REQUEST_URI'] variable. This seems to fix it:

if(!isset($_SERVER['REQUEST_URI'])) {
    $_SERVER['REQUEST_URI'] = substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1);
}

Clases Predefinidas> <Lista de Palabras Reservadas
Last updated: Tue, 27 Nov 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites