PHP - Superglobal arrays

  »   PHP Introduction  »   PHP Tutorial - Superglobal arrays

Superglobals are a type of variables that are aveilable from any part of your code. Some are well known like POST and GET that are used to pass form values and COOKIE and SESSION that are used to store specific information for a later use.

Here are all the superglobals that are all available for you to use from within your functions, classes, file or anywhere else, without any other requirements on your behalf.

  • $_SERVER - An array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.
  • $_REQUEST - An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
  • $_POST - An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
  • $_GET - An associative array of variables passed to the current script via the URL parameters (query string).
  • $_COOKIE - An associative array of variables passed to the current script via HTTP Cookies..
  • $_SESSION - An associative array containing session variables available to the current script.
  • $_FILES - An associative array of items uploaded to the current script via the HTTP POST method.
  • $GLOBALS - An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
  • $_ENV - An associative array of variables passed to the current script via the environment method.
  • $http_response_header - is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope.
  • $argc - The number of arguments passed to script
  • $argv - Array of arguments passed to script

Now let's explain and see some examples of usage of the most important superglobals

PHP superglobals - $GLOBALS

PHP $GLOBALS it's an associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

Here is an example of how to use the PHP $GLOBALS superglobal:

php<?php 
$a = "Hello"; 
$b = "world";
 
function say_hello() { 
    $GLOBALS['c'] = $GLOBALS['a'] + " " + $GLOBALS['y']; 
}
 
say_hello(); 
echo $c; 
?>

$GLOBALS makes the $c variable accesible from outside the function.

PHP superglobals - $_SERVER

PHP $_SERVER An array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.

Here is an example of how to use the PHP $_SERVER superglobal:

php<?php 
echo "<pre>";
print_r($_SERVER);
echo "</pre>";
?>

We are printing here our localhost $_SERVER array to see all the information that contains.

phpArray
(
    [MIBDIRS] => C:/xampp/php/extras/mibs
    [MYSQL_HOME] => \xampp\mysql\bin
    [OPENSSL_CONF] => C:/xampp/apache/bin/openssl.cnf
    [PHP_PEAR_SYSCONF_DIR] => \xampp\php
    [PHPRC] => \xampp\php
    [TMP] => \xampp\tmp
    [HTTP_HOST] => localhost
    [HTTP_CONNECTION] => keep-alive
    [HTTP_CACHE_CONTROL] => max-age=0
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
    [HTTP_DNT] => 1
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng
    [HTTP_ACCEPT_ENCODING] => gzip, deflate, br
    [HTTP_ACCEPT_LANGUAGE] => es,en-US;q=0.9,en;q=0.8,ro;q=0.7,fr;q=0.6
    [HTTP_COOKIE] => 
    [PATH] => C:\Program Files (x86)\Common Files\Oracle\Java\javapath
    [SystemRoot] => C:\WINDOWS
    [COMSPEC] => C:\WINDOWS\system32\cmd.exe
    [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    [WINDIR] => C:\WINDOWS
    [SERVER_SIGNATURE] => Apache/2.4.29 (Win32) OpenSSL/1.0.2l PHP/5.6.32 Server at localhost Port 80
    [SERVER_SOFTWARE] => Apache/2.4.29 (Win32) OpenSSL/1.0.2l PHP/5.6.32
    [SERVER_NAME] => localhost
    [SERVER_ADDR] => ::1
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => ::1
    [DOCUMENT_ROOT] => C:/xampp/htdocs
    [REQUEST_SCHEME] => http
    [CONTEXT_PREFIX] => 
    [CONTEXT_DOCUMENT_ROOT] => C:/xampp/htdocs
    [SERVER_ADMIN] => postmaster@localhost
    [SCRIPT_FILENAME] => C:/xampp/htdocs/tools/_php/test_server.php
    [REMOTE_PORT] => 52404
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => GET
    [QUERY_STRING] => 
    [REQUEST_URI] => /tools/_php/test_server.php
    [SCRIPT_NAME] => /tools/_php/test_server.php
    [PHP_SELF] => /tools/_php/test_server.php
    [REQUEST_TIME_FLOAT] => 1538043806.399
    [REQUEST_TIME] => 1538043806
)

Now this is really lots of variables to deal with and remember. Let's take a look at some of the most important $_SERVER keys:

KEYDescription
PHP_SELFfilename for the currently executing script
SERVER_ADDRIP address of the host
SERVER_NAMEname of the host
REQUEST_METHODthe request method used to access the page (POST or GET for example)
QUERY_STRINGReturns the query string if the page is accessed via query string
HTTP_HOSThost headers
HTTP_REFERERcomplete URL of the referrer page
REMOTE_ADDRuser IP
SCRIPT_FILENAMEabsolute pathname of the currently executing script

PHP superglobals - $_REQUEST

$_REQUEST superglobal is used to store values of all input fields of a submitted form. Let's assume a simple form that a user can use to send some info to your server for further processing:

php<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
	Name: <input type="text" name="name">
	Message: <input type="text" name="message">
	<input type="submit" value="Send">
</form>

Let's see what happens when the user hit the "Send" button:

php<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name 	= $_REQUEST['name'];
    $message= $_REQUEST['message'];

    if (empty($name)) {
        echo "Name is empty";
    } elseif (empty($message)) {
    	 echo "Message is empty";
    } else {
        echo "Hello $name, here is your message: $message";
    }
}
?>

Here we just check if the user arrives at the current page via POST method. If it has, we collect the data and check for empty fields. Give it a try and play with this code for a while before continuing.

PHP superglobals - $_POST

$_POST is one of the most used methods to collect data using a form and to pass data from one endpoint to another. Here is a simple example using the POST method in PHP.

php<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
	Name: <input type="text" name="name">
	Message: <input type="text" name="message">
	<input type="submit" value="Send">
</form>
php<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name 	= $_POST['name'];
    $message= $_POST['message'];

    if (empty($name)) {
        echo "Name is empty";
    } elseif (empty($message)) {
    	 echo "Message is empty";
    } else {
        echo "Hello $name, here is your message: $message";
    }
}
?>

PHP superglobals - $_GET

Just like POST, GET is commonly used to collect data sent by HTML forms or using queries in the URL. Here is an example using GET to collect data from a form

php<form method="get" action="<?php echo $_SERVER['PHP_SELF'];?>">
	Name: <input type="text" name="name">
	Message: <input type="text" name="message">
	<input type="submit" value="Send">
</form>
php<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {

    $name 	= $_GET['name'];
    $message= $_GET['message'];

    if (empty($name)) {
        echo "Name is empty";
    } elseif (empty($message)) {
    	 echo "Message is empty";
    } else {
        echo "Hello $name, here is your message: $message";
    }
}
?>

To pass params via URL query using GET method, take a look a the following example.

php<a href="hello.php?name=John&location=Missouri">Say Hello</a>

And here is how you can recover them

php<?php
    $name 	= $_GET['name'];
    $location= $_GET['location'];

    echo "Hello $name form $location";
?>

Security concerns when using POST or GET

When using GET or POST method there is a serious concern about security. Actually every time you insert data coming from a user you are in serious danger. If you do not protect your form or application, a hacker can easily upload a shell or write data to your database (SQL injection). So make sure you escape and filter your data when collecting it or sending it to the database