HOME HTML EDITOR C JAVA PHP

PHP Superglobals

Superglobals are built-in variables that are always available in all scopes. This means you can access them from any function, class, or file without having to do anything special.

1. What are Superglobals?

Several predefined variables in PHP are "superglobals", which means they are global variables that are accessible regardless of scope. The most common ones are:

2. $GLOBALS

$GLOBALS is used to access global variables from anywhere in the PHP script. PHP stores all global variables in an array called $GLOBALS[index].

<?php
  $x = 75;
  $y = 25;

  function addition() {
    $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
  }

  addition();
  echo $z; // Outputs: 100
?>

3. $_SERVER

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

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

4. $_POST and $_GET

These are used to collect form data. $_POST is used for sending sensitive data (hidden from URL), while $_GET sends data through the URL parameters.

<?php
  // Collecting data from a form field named 'fname'
  $name = $_POST['fname'];
  echo $name;
?>

5. $_SESSION

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is stored on the server.

<?php
  session_start();
  $_SESSION["username"] = "ExpertAdmin";
  echo "Session variable is set.";
?>
Security Tip: Always validate and sanitize data received via $_GET and $_POST to protect your website from SQL Injection and Cross-Site Scripting (XSS) attacks.