PHP Global Variables

PHP Global Variables

In Php predefined variable that they are always accessible called Global vaiable. In Php there are many global variable. Some of them are explaind in this tutorail.

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

1. PHP $GLOBALS

$GLOBALS is a PHP global variable which is used to access global variables from within functions or methods or we can say anywhere in php script.
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

Example

<?php
$x = 100;
$y = 200;
function addition() {
$GLOBALS[‘z’] = $GLOBALS[‘x’] + $GLOBALS[‘y’];
}
addition();
echo $z;
?>

2. PHP $_SERVER

$_SERVER is a PHP global variable which holds information about headers, paths, and script locations.

Example of $_SERVER

<?php 
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

3. PHP $_REQUEST

PHP $_REQUEST is used to collect data from a submitted HTML form.

Example of $_REQUEST

<html>
<body>
 
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="firstname">
  <input type="submit">
</form>
 
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_REQUEST['firstname'];
    if (empty($name)) {
        echo "Name is blank";
    } else {
        echo $name;
    }
}
?>
 
</body>
</html>