As we have discussed PHP Global variables. Some PHP variables are “superglobals,” which means they are always reachable, irrespective of scope, and can be accessed from any function, class, or file without doing anything special.
PHP Superglobal Variables
The superglobals can be found all across your script. These variables can be accessed from any function, class, or file without the need to perform any further steps, such as creating a global variable. They are mostly employed in applications to save and retrieve data from one page to the next.
The following are the PHP superglobal variables:
- $GLOBALS
- $_SERVER
- $_REQUEST
- $_POST
- $_GET
- $_FILES
- $_ENV
- $_COOKIE
- $_SESSION
Let’s discuss some of the mainly used superglobals in detail.
1. $GLOBALS
It’s a superglobal variable that is used to access global variables from anywhere in the PHP script.
All global variables are stored in the array $GLOBALS[index], where the index is the global variable name that can be retrieved.
The following example demonstrates how to use $GLOBALS in PHP:
<h2>Example of $GLOBALS</h2> <?php $x = 10; $y = 5; function division() { $GLOBALS['d'] = $GLOBALS['x'] / $GLOBALS['y']; } division(); echo $d; ?>
In the example above, since d is a variable present within the $GLOBALS array, it can also be accessed from outside the function.
2. $_SERVER
The PHP super global variable $_SERVER stores information about headers, paths, and script locations.
We will discuss $_SERVER in detail in the next chapter.
3. $_Request
PHP $_REQUEST is a super global variable used to collect data after an HTML form is submitted.
$_REQUEST is rarely used, because $_POST and $_GET perform the same operation and are frequently used.
To demonstrate how $_REQUEST works, below is the HTML and PHP code:
4. $_Post
PHP $_POST is a PHP super global variable that collects form data once an HTML form with method=”post” is submitted. Variables are also commonly passed using $_POST.
When the form uses post method for data transfer, the data is not visible in connection with the query, due to which the level of security is maintained in this procedure.
4. $_Get
PHP $_GET is a PHP super global variable that collects form data once an HTML form with method=”get” is submitted.
Data sent via the URL can also be collected with $_GET.