PHP Superglobals are predefined global variables that are found within the PHP library. They can be accessed at any point of the program.

PHP Superglobals :

PHP superglobals are callable from whatever scope, whether it is within a class, function, or separate file.

There exists a list of PHP superglobals which are basic and commonly used. They are always written in capital letters.

PHP $GLOBALS :

This superglobal variable is used whenever there is the need to access global variables from anywhere within a PHP source script.

PHP reserves the global variables within a single array named $GLOBALS[index], where index represents the name of the specific variable.


<?php
$i = 12;
$j = 46;

function sum() {
$GLOBALS['x'] = $GLOBALS['i'] + $GLOBALS['j'];
}
sum();
echo "Addition : ". $x;
?>

Output:

Addition : 58

PHP $_SERVER :

This suberglobal variable is used to hold information related to paths, headers, and script locations in PHP.

<?
php echo $_SERVER['HTTP_HOST']."</br>"; 
echo $_SERVER['SERVER_NAME']."</br>"; 
echo $_SERVER['SERVER_PORT']."</br>"; 
?>

Output:

localhost
localhost
80

The above code extracts information from the server and presents it on the browser, which is represented by port 8080; as below:

There are many other $_SERVER[]; superglobals existent in PHP.

They are listed below :

$_SERVER[‘SERVER_ADDR’] Returns the host server IP address

$_SERVER[‘PHP_SELF’] Displays the filename of the script being executed.

$_SERVER[‘SERVER_SOFTWARE’] Displays the server identification string.

These are few examples of the server-related superglobals. Refer to the Reference section for more Server superglobals.

PHP $_REQUEST[]

It is a variable that is used to collect information after the submission of an HTML form.

$_POST[]

It is a superglobal variable used in forms for data collection after submission of HTML forms. It can be used to pass variables. It is used with the method=”post”

$_GET[]

It is commonly used with forms too, through the method=”get”. It can obtain hyperlinks and URLs to certain documents both online and offline.

Examples of the globals above are embedded within the following program:


<html>
    <body>

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

        <?php
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $name = $_POST['textarea'];
            if (empty($name)) {
                echo "Please enter name";
            } else {
                echo $name;
            }
        }
        ?>
    </body>
</html>

Output :

PHP SuperglobalsHappy Learning 🙂