Superglobals in PHP

Superglobals are per-defined variables in PHP and they are always accessible.

The PHP superglobal variables are :
  • $_SERVER
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE

$_GLOBALS : It is used to access global variables from anywhere in the PHP script.

Example :
$x = 15;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
echo "Sum is : ".$z;

Output :
Sum is : 40

$_SERVER : $_SERVER holds information about headers, paths, and script locations.

Example :
echo "Server Address : ".$_SERVER['SERVER_ADDR'];
echo "<br>";
// Retrieves the client browser type, version number, library, and platform the browser is configured for.

Output :
Server Address :
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0

The following table lists the most important elements that can be use inside $_SERVER :

Element Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as Apache/2.4.39 (Win64) OpenSSL/1.1.1c PHP/7.3.7)
$_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)y
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
$_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['SERVER_PORT'] Returns the port on the server machine being used by the web server (such as 80)
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page

$_REQUEST : It is used to collect data after submitting an HTML form.

Example :
<!DOCTYPE html>
<form action="" method="post" style="text-align:center;">
      <td><input type="text" name="fname" placeholder="Enter your Name"></td>
  </tr><br />
      <input type="submit" name="submit" value="Submit">
      // collect value of input field
      $name = $_REQUEST['fname'];
            echo "Welcome ".$name;

Output :

The remaining superglobals variable are not discussed in this tutorials.