Ves al contingut principal

Objecte SERVER

L'objecte $_SERVER a PHP és un array global que conté informació sobre l'entorn del servidor i l'execució del script. Les seves dades varien en funció de si el script s'executa des d'un servidor web o des de la línia de comandes. S'utilitza per obtenir informació com ara l'adreça IP del client, el nom del servidor, la ruta del script, i els headers HTTP de la petició.

Funcions principals i elements

Aquest array associatiu es crea automàticament per PHP i conté una gran varietat de dades útils. . La seva utilitat rau en la capacitat de proporcionar informació contextual per a la lògica de l'aplicació. A continuació, es detallen alguns dels seus elements més comuns i les seves funcions:

Element Funció Exemple de valor
$_SERVER['REQUEST_METHOD'] Indica el mètode de la petició HTTP utilitzat per accedir a la pàgina (per exemple, GET, POST, PUT). GET
$_SERVER['PHP_SELF'] Retorna el nom del fitxer del script que s'està executant, relatiu a la carpeta arrel del document. /carpeta/fitxer.php
$_SERVER['HTTP_HOST'] Conté el nom de domini del servidor al qual s'ha enviat la petició. www.exemple.cat
$_SERVER['SERVER_NAME'] Retorna el nom del servidor host. En un entorn de hosting compartit, pot ser diferent d'HTTP_HOST. www.exemple.cat
$_SERVER['SERVER_ADDR'] Proporciona l'adreça IP del servidor on s'executa el script. 192.168.1.100
$_SERVER['REMOTE_ADDR'] Retorna l'adreça IP del client que ha realitzat la petició a la pàgina. 123.45.67.89
$_SERVER['DOCUMENT_ROOT'] Indica la ruta absoluta del directori arrel del document del servidor. /var/www/html
$_SERVER['QUERY_STRING'] Conté la part de la URL que ve després del signe d'interrogació (?). id=123&nom=joan
$_SERVER['HTTP_USER_AGENT'] Proporciona informació sobre el navegador web i el sistema operatiu del client. Mozilla/5.0 (Windows NT 10.0; ...)
$_SERVER['SCRIPT_FILENAME'] Retorna el nom absolut de la ruta del script actual que s'està executant. /var/www/html/carpeta/fitxer.php

Elements que no es recomana emprar per seguretat

Tot i la seva utilitat, l'ús d'alguns elements de $_SERVER pot ser perillós si no es manipulen correctament, ja que es poden falsificar fàcilment. L'ús inadequat d'aquestes variables pot portar a vulnerabilitats com ara atacs de cross-site scripting (XSS). És fonamental validar i sanititzar sempre qualsevol dada obtinguda a través d'aquestes variables. .

Aquests són els elements que s'han d'usar amb precaució:

  • $_SERVER['PHP_SELF']: Aquesta variable és especialment susceptible a atacs XSS. Un atacant podria injectar codi maliciós a la URL, que seria retornat per aquesta variable i executat en el navegador del client. Per exemple, si s'utilitza en un formulari d'acció (<form action="<?php echo $_SERVER['PHP_SELF']; ?>">), un atacant podria afegir codi com ara "><script>alert('XSS');</script> a la URL, tancant l'etiqueta HTML i injectant codi JavaScript.

  • $_SERVER['HTTP_HOST']: Aquesta variable pot ser manipulada per un atacant a través dels headers de la petició. Si s'utilitza per construir URLs absolutes, es podria aconseguir que el lloc web generi enllaços cap a un domini controlat per l'atacant, facilitant atacs de phishing o cache poisoning.

  • $_SERVER['REQUEST_URI']: Similar a PHP_SELF, pot contenir dades malicioses injectades a la URL pel client. S'ha de tractar amb molta precaució.

  • $_SERVER['REMOTE_ADDR']: Encara que útil per obtenir l'IP del client, pot ser falsificada en peticions que passen per servidors proxy. Per obtenir la IP real del client en aquests casos, s'haurien de comprovar altres headers com ara X-Forwarded-For, que també poden ser falsificats.

Per mitigar aquests riscos, s'han de sanititzar i validar sempre les dades rebudes, utilitzant funcions com htmlspecialchars() per evitar l'execució de codi HTML/JavaScript i filtres de validació (filter_var()) quan sigui possible.

Altres elements de capçalera

Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (CGI) the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as www.w3schools.com)
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol (such as HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (such as POST)
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as 1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1)
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable because not all user-agents support it)
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to communicate with the web server
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing script
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on a virtual host, it will be the value defined for that virtual host) (such as someone@w3schools.com)
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web server for communication (such as 80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which are added to server-generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page

Quines variables tinc?

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Server variable</title>
   </head>
   <body>
      <h1>VARIABLE $_SERVER</h1>
      
      <?php
         foreach ($_SERVER as $key => $value) {
            echo "<strong>$key</strong>: " . $value . "<br/>";
         }   
      ?>

   </body>
</html>