PHP Global Variables (Superglobals)

Global Variables are built-in variables that are always available. We can use them anywhere in Project(function, class or file).

PHP Global Variables are:

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

$GLOBALS

$GLOBALS is used to access global variables from anywhere in php script.

    <?php    
        $a = 1;
        $b = 2;
        function sum() {
            $GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
        }
        sum();
        echo $c;
        Output is 3

        //another way to access global varible
        $a = 1;
        $b = 2;
        function sum() {
            global $a, $b, $c;
            $c = $a + $b;
        }
        sum();
        echo $c;
        Output is 3
    ?>

$_SERVER

$_SERVER is used to get information about headers, paths, and script locations.

    <?php 
        echo $_SERVER['PHP_SELF'];
    ?>

$_GET, $_POST and $_REQUEST

$_GET, $_POST and $_REQUEST are used to collect form-data

PHP Tutorial